Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Đối tượng File trong Java – Tạo, thao tác và lấy thông tin file

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

ConstructorMô 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

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);
    }
}
Phương thứcTrả vềMô tả
getName()StringTê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()StringThư mục cha (null nếu root).
exists()booleanFile/thư mục có tồn tại không.
isFile() / isDirectory()booleanKiểm tra loại.
canRead() / canWrite() / canExecute()booleanQuyền truy cập.
length()longKích thước file (bytes). Thư mục trả về 0.
lastModified()longTimestamp sửa đổi cuối (ms từ epoch).
list() / listFiles()String[] / File[]Liệt kê con (chỉ thư mục).
mkdir() / mkdirs()booleanTạo thư mục (mkdirs tạo cả cha).
createNewFile()booleanTạo file rỗng nếu chưa tồn tại.
delete()booleanXóa file/thư mục rỗng.
renameTo(File dest)booleanĐổi tên/di chuyển.