Jave Tut 45 : Xử lý tệp Java ( Java Files)

0
0
(0)

Xử lý tệp là một phần quan trọng của bất kỳ ứng dụng nào.

Java có một số phương pháp để tạo, đọc, cập nhật và xóa tệp.


Xử lý tệp Java

Các Filelớp từ java.iogói, cho phép chúng tôi làm việc với các tập tin.

Để sử dụng Filelớp, hãy tạo một đối tượng của lớp và chỉ định tên tệp hoặc tên thư mục:

Thí dụ

import java.io.File;  // Import the File class

File myObj = new File("filename.txt"); // Specify the filename

Nếu bạn không biết gói là gì, hãy đọc Hướng dẫn về gói Java của chúng tôi .

Các Filelớp học có nhiều phương pháp hữu ích cho việc tạo ra và nhận được thông tin về các tập tin. Ví dụ:

MethodTypeDescription
canRead()BooleanTests whether the file is readable or not
canWrite()BooleanTests whether the file is writable or not
createNewFile()BooleanCreates an empty file
delete()BooleanDeletes a file
exists()BooleanTests whether the file exists
getName()StringReturns the name of the file
getAbsolutePath()StringReturns the absolute pathname of the file
length()LongReturns the size of the file in bytes
list()String[]Returns an array of the files in the directory
mkdir()BooleanCreates a directory

Tạo tệp

Để tạo một tệp trong Java, bạn có thể sử dụng createNewFile()phương pháp này. Phương thức này trả về giá trị boolean: truenếu tệp được tạo thành công và falsenếu tệp đã tồn tại. Lưu ý rằng phương thức được bao bọc trong một try...catch khối. Điều này là cần thiết vì nó ném ra một IOExceptionlỗi nếu xảy ra (nếu không thể tạo tệp vì lý do nào đó):

Thí dụ

import java.io.File;  // Import the File class
import java.io.IOException;  // Import the IOException class to handle errors

public class CreateFile {
  public static void main(String[] args) {
    try {
      File myObj = new File("filename.txt");
      if (myObj.createNewFile()) {
        System.out.println("File created: " + myObj.getName());
      } else {
        System.out.println("File already exists.");
      }
    } catch (IOException e) {
      System.out.println("An error occurred.");
      e.printStackTrace();
    }
  }
}

Đầu ra sẽ là:File created: filename.txtChạy ví dụ »

Để tạo tệp trong một thư mục cụ thể (yêu cầu quyền), hãy chỉ định đường dẫn của tệp và sử dụng dấu gạch chéo ngược kép để thoát khỏi \ký tự “” (đối với Windows). Trên Mac và Linux, bạn chỉ có thể viết đường dẫn, như: /Users/name/filename.txt

Thí dụ

File myObj = new File("C:\\Users\\MyName\\filename.txt");

Chạy ví dụ »


Ghi vào tệp

Trong ví dụ sau, chúng tôi sử dụng FileWriterlớp cùng với write()phương thức của nó để ghi một số văn bản vào tệp mà chúng tôi đã tạo trong ví dụ trên. Lưu ý rằng khi bạn ghi xong tệp vào tệp, bạn nên đóng tệp bằng close()phương pháp:

Thí dụ

import java.io.FileWriter;   // Import the FileWriter class
import java.io.IOException;  // Import the IOException class to handle errors

public class WriteToFile {
  public static void main(String[] args) {
    try {
      FileWriter myWriter = new FileWriter("filename.txt");
      myWriter.write("Files in Java might be tricky, but it is fun enough!");
      myWriter.close();
      System.out.println("Successfully wrote to the file.");
    } catch (IOException e) {
      System.out.println("An error occurred.");
      e.printStackTrace();
    }
  }
}

Đầu ra sẽ là:Successfully wrote to the file.Chạy ví dụ »

Đọc tệp

Trong chương trước, bạn đã học cách tạo và ghi vào một tệp.

Trong ví dụ sau, chúng tôi sử dụng Scannerlớp để đọc nội dung của tệp văn bản mà chúng tôi đã tạo trong chương trước:

Thí dụ

import java.io.File;  // Import the File class
import java.io.FileNotFoundException;  // Import this class to handle errors
import java.util.Scanner; // Import the Scanner class to read text files

public class ReadFile {
  public static void main(String[] args) {
    try {
      File myObj = new File("filename.txt");
      Scanner myReader = new Scanner(myObj);
      while (myReader.hasNextLine()) {
        String data = myReader.nextLine();
        System.out.println(data);
      }
      myReader.close();
    } catch (FileNotFoundException e) {
      System.out.println("An error occurred.");
      e.printStackTrace();
    }
  }
}

Đầu ra sẽ là:Files in Java might be tricky, but it is fun enough!Chạy ví dụ »


Nhận thông tin tệp

Để biết thêm thông tin về tệp, hãy sử dụng bất kỳ Filephương pháp nào:

Thí dụ

import java.io.File;  // Import the File class

public class GetFileInfo {   public static void main(String[] args) {
    File myObj = new File("filename.txt");
    if (myObj.exists()) {
      System.out.println("File name: " + myObj.getName());
      System.out.println("Absolute path: " + myObj.getAbsolutePath());
      System.out.println("Writeable: " + myObj.canWrite());
      System.out.println("Readable " + myObj.canRead());
      System.out.println("File size in bytes " + myObj.length());
    } else {
      System.out.println("The file does not exist.");
    }
  }
}

Đầu ra sẽ là:File name: filename.txt
Absolute path: C:\Users\MyName\filename.txt
Writeable: true
Readable: true
File size in bytes: 0
Chạy ví dụ »

Lưu ý: Có nhiều lớp có sẵn trong Java API có thể được sử dụng để đọc và ghi tệp trong Java:, FileReader, BufferedReader, Files, Scanner, FileInputStream, FileWriter, BufferedWriter, FileOutputStreamv.v. Sử dụng lớp nào tùy thuộc vào phiên bản Java mà bạn đang làm việc và liệu bạn cần đọc byte hay ký tự, và kích thước của tệp / dòng, v.v.

Mẹo: Để xóa một tệp, hãy đọc chương Xóa tệp trong Java .

Xóa tệp

Để xóa một tệp trong Java, hãy sử dụng delete()phương pháp:

Thí dụ

import java.io.File;  // Import the File class

public class DeleteFile {
  public static void main(String[] args) { 
    File myObj = new File("filename.txt"); 
    if (myObj.delete()) { 
      System.out.println("Deleted the file: " + myObj.getName());
    } else {
      System.out.println("Failed to delete the file.");
    } 
  } 
}

Đầu ra sẽ là:Deleted the file: filename.txtChạy ví dụ »


Xóa một thư mục

Bạn cũng có thể xóa một thư mục. Tuy nhiên, nó phải trống:

Thí dụ

import java.io.File; 

public class DeleteFolder {
  public static void main(String[] args) { 
    File myObj = new File("C:\\Users\\MyName\\Test"); 
    if (myObj.delete()) { 
      System.out.println("Deleted the folder: " + myObj.getName());
    } else {
      System.out.println("Failed to delete the folder.");
    } 
  } 
}

Đầu ra sẽ là:Deleted the folder: TestChạy ví dụ »

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

Leave A Reply

Your email address will not be published.