Lớp java.io.File đại diện cho đường dẫn file hoặc thư mục (directory) trên hệ thống file. Quan trọng: File object không đọc/ghi nội dung file – nó chỉ đại diện cho metadata (tên, đường dẫn, quyền, kích thước...). Để đọc/ghi, dùng FileInputStream, FileReader, Files (NIO.2).
Các Constructor phổ biến
| Constructor | Mô tả |
File(String pathname) | Tạo từ đường dẫn tuyệt đối hoặc tương đối (chuỗi). |
File(String parent, String child) | Tạo từ đường dẫn cha và tên con. |
File(File parent, String child) | Từ File object cha và tên con. |
File(URI uri) | Từ URI (file://...). |
Phương thức thông dụng
| Phương thức | Trả về | Mô tả |
getName() | String | Tên file/thư mục (không có đường dẫn). |
getPath() | String | Đường dẫn như khi tạo (relative/absolute). |
getAbsolutePath() | String | Đường dẫn tuyệt đối chuẩn hóa. |
getParent() | String | Thư mục cha (null nếu root). |
exists() | boolean | File/thư mục có tồn tại không. |
isFile() / isDirectory() | boolean | Kiểm tra loại. |
canRead() / canWrite() / canExecute() | boolean | Quyền truy cập. |
length() | long | Kích thước file (bytes). Thư mục trả về 0. |
lastModified() | long | Timestamp sửa đổi cuối (ms từ epoch). |
list() / listFiles() | String[] / File[] | Liệt kê con (chỉ thư mục). |
mkdir() / mkdirs() | boolean | Tạo thư mục (mkdirs tạo cả cha). |
createNewFile() | boolean | Tạo file rỗng nếu chưa tồn tại. |
delete() | boolean | Xóa file/thư mục rỗng. |
renameTo(File dest) | boolean | Đổi tên/di chuyển. |
Ví dụ minh họa
import java.io.File;
import java.text.SimpleDateFormat;
public class FileDemo {
public static void main(String[] args) {
// Tạo File object từ tham số command line hoặc hardcode
String path = args.length > 0 ? args[0] : "test.txt";
File file = new File(path);
System.out.println("=== File Information ===");
System.out.println("Name: " + file.getName());
System.out.println("Path: " + file.getPath());
System.out.println("Absolute Path: " + file.getAbsolutePath());
System.out.println("Parent: " + file.getParent());
if (file.exists()) {
System.out.println("Exists: YES");
System.out.println("Is File: " + file.isFile());
System.out.println("Is Directory: " + file.isDirectory());
System.out.println("Readable: " + file.canRead());
System.out.println("Writable: " + file.canWrite());
System.out.println("Size (bytes): " + file.length());
System.out.println("Last Modified: " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(file.lastModified()));
if (file.isDirectory()) {
System.out.println("\nContents:");
File[] children = file.listFiles();
if (children != null) {
for (File child : children) {
System.out.printf(" %s %s (%d bytes)%n",
child.isDirectory() ? "[DIR]" : "[FILE]",
child.getName(), child.length());
}
}
}
} else {
System.out.println("Exists: NO");
// Tạo file/demo
try {
if (file.createNewFile()) {
System.out.println("Created empty file: " + file.getAbsolutePath());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Lưu ý quan trọng
File không kiểm tra sự tồn tại khi tạo – chỉ tạo object đại diện cho path.
- Đường dẫn: dùng
File.separator (hoặc / – Java hiểu cross-platform) thay vì hardcode \ hoặc /.
- Java 7+ NIO.2 (
java.nio.file.Files, Path, Paths) mạnh hơn, expressive hơn, hỗ trợ symbolic links, attributes, async I/O. Khuyên dùng cho code mới.
Ví dụ NIO.2 (Modern)
import java.nio.file.*;
import java.io.IOException;
public class NioFileDemo {
public static void main(String[] args) throws IOException {
Path path = Paths.get("test.txt");
// Kiểm tra tồn tại
System.out.println("Exists: " + Files.exists(path));
// Đọc toàn bộ file (text)
String content = Files.readString(path);
System.out.println("Content: " + content);
// Ghi file
Files.writeString(path, "Hello NIO.2!", StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
// Walk directory
Files.walk(Paths.get("."))
.filter(Files::isRegularFile)
.forEach(System.out::println);
}
}