Class java.io.File แทน **Path/ไฟล์/ไดเรกทอรี** ใน File System ไม่ใช่เนื้อหาไฟล์ ใช้สำหรับ metadata และ file system operations
Constructors
| Constructor | คำอธิบาย |
File(String pathname) | สร้างจาก path string (absolute/relative) |
File(String parent, String child) | สร้างจาก parent path + child name |
File(File parent, String child) | สร้างจาก parent File object + child name |
File(URI uri) | สร้างจาก file: URI |
ตัวอย่างการใช้งาน
import java.io.File;
import java.io.IOException;
public class FileObjectDemo {
public static void main(String[] args) {
// 1. สร้าง File objects ด้วย constructors ต่างๆ
File f1 = new File("test.txt"); // Relative path
File f2 = new File("/home/user/documents/test.txt"); // Absolute path
File f3 = new File("/home/user/documents", "test.txt"); // Parent + child
File f4 = new File(f3.getParentFile(), "another.txt"); // File parent + child
// 2. Path information
System.out.println("Name: " + f1.getName()); // test.txt
System.out.println("Path: " + f1.getPath()); // test.txt
System.out.println("Absolute Path: " + f1.getAbsolutePath()); // /current/dir/test.txt
System.out.println("Parent: " + f1.getParent()); // null (relative)
System.out.println("Canonical: " + f1.getCanonicalPath()); // Resolved absolute
// 3. File existence & properties
File existing = new File("/etc/passwd"); // Linux system file
if (existing.exists()) {
System.out.println("Exists: Yes");
System.out.println("Is File: " + existing.isFile());
System.out.println("Is Directory: " + existing.isDirectory());
System.out.println("Readable: " + existing.canRead());
System.out.println("Writable: " + existing.canWrite());
System.out.println("Executable: " + existing.canExecute());
System.out.println("Size: " + existing.length() + " bytes");
System.out.println("Last Modified: " + new Date(existing.lastModified()));
}
// 4. Directory operations
File dir = new File("myapp/data");
if (!dir.exists()) {
boolean created = dir.mkdirs(); // สร้าง parent directories ด้วย
System.out.println("Directory created: " + created);
}
// List files
File[] files = dir.listFiles();
if (files != null) {
for (File file : files) {
System.out.println(file.getName() + " - " + (file.isDirectory() ? "[DIR]" : "[FILE]"));
}
}
// Filter listing
File[] txtFiles = dir.listFiles((d, name) -> name.endsWith(".txt"));
File[] dirs = dir.listFiles(File::isDirectory);
}
}
File Operations
| Operation | Method | Return |
| Create file | createNewFile() | boolean |
| Create directory | mkdir() / mkdirs() | boolean |
| Delete | delete() | boolean |
| Delete on exit | deleteOnExit() | void (JVM shutdown hook) |
| Rename/Move | renameTo(File dest) | boolean |
| Set permissions | setReadable/Writeable/Executable() | boolean |
| Set last modified | setLastModified(long time) | boolean |
สร้างไฟล์ชั่วคราว (Temp Files)
// สร้าง temp file ใน default temp directory
File tempFile = File.createTempFile("myapp-", ".tmp");
tempFile.deleteOnExit(); // ลบตอน JVM ปิด
// สร้าง temp directory
File tempDir = Files.createTempDirectory("myapp-").toFile();
tempDir.deleteOnExit();
Path vs File (Java 7+ NIO.2)
แนะนำใช้ java.nio.file.Path และ Files แทน File class
| File (Legacy) | Path/Files (Modern) |
new File(path) | Paths.get(path) หรือ Path.of(path) (Java 11+) |
file.exists() | Files.exists(path) |
file.length() | Files.size(path) |
file.delete() | Files.delete(path) / Files.deleteIfExists(path) |
file.renameTo() | Files.move(src, dest, REPLACE_EXISTING) |
file.listFiles() | Files.list(path) (Stream) / Files.walk() |
| ไม่มี symbolic link support | รองรับ Symbolic Links, Attributes, ACLs |
| Boolean return (ไม่รู้สาเหตุ) | Throw Exception (รู้สาเหตุ失敗) |
NIO.2 Files Example
import java.nio.file.*;
import java.io.IOException;
import java.util.stream.Stream;
public class NioFileExample {
public static void main(String[] args) throws IOException {
Path path = Path.of("data", "config.json");
// Read all lines
List lines = Files.readAllLines(path);
// Read as String (Java 11+)
String content = Files.readString(path);
// Write
Files.writeString(path, "New content", StandardOpenOption.CREATE, StandardOpenOption.WRITE);
Files.write(path, List.of("Line 1", "Line 2"), StandardOpenOption.APPEND);
// Walk directory (Stream)
try (Stream paths = Files.walk(Paths.get("data"))) {
paths.filter(Files::isRegularFile)
.filter(p -> p.toString().endsWith(".json"))
.forEach(System.out::println);
}
// Copy/Move with options
Files.copy(Paths.get("src.txt"), Paths.get("dest.txt"), StandardCopyOption.REPLACE_EXISTING);
Files.move(Paths.get("old.txt"), Paths.get("new.txt"), StandardCopyOption.ATOMIC_MOVE);
}
}
สรุป
java.io.File - Legacy, ใช้สำหรับ metadata/path operations แบบง่าย
java.nio.file.Path + Files - **Modern API**, รองรับทุกอย่าง, Exception handling ดีกว่า, Stream support
- โค้ดใหม่ควรใช้ NIO.2 ทั้งหมด