Tệp Java
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
Lớp File
từ java.io
gói, cho phép chúng tôi làm việc với các tệp.
Để sử dụng File
lớ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 .
Lớp File
có nhiều phương thức hữu ích để tạo và lấy thông tin về tệp. Ví dụ:
Method | Type | Description |
---|---|---|
canRead() |
Boolean | Tests whether the file is readable or not |
canWrite() |
Boolean | Tests whether the file is writable or not |
createNewFile() |
Boolean | Creates an empty file |
delete() |
Boolean | Deletes a file |
exists() |
Boolean | Tests whether the file exists |
getName() |
String | Returns the name of the file |
getAbsolutePath() |
String | Returns the absolute pathname of the file |
length() |
Long | Returns the size of the file in bytes |
list() |
String[] | Returns an array of the files in the directory |
mkdir() |
Boolean | Creates a directory |
Bạn sẽ học cách tạo, viết, đọc và xóa tệp trong các chương tiếp theo: