Java 7 引入 java.nio.file 套件(NIO.2),提供現代化、鏈式、異步支援、屬性豐富的文件系統 API。核心類別 Path、Files、FileSystem 徹底取代舊式 java.io.File。本文實戰演示四大核心操作與權限屬性設置。
Path:文件系統路御邏輯抽象(替代 File),不可變、線程安全。Files:靜態工具方法集,所有操作入口。FileSystems:獲取預設/自定義文件系統。
Path target = Paths.get("D:/Backup/MyStuff.txt");
Path file = Files.createFile(target); // 拋出 FileAlreadyExistsException 若已存在
Path target = Paths.get("/backup/data.txt");
Set perms = PosixFilePermissions.fromString("rw-rw-rw-"); // u=rw,g=rw,o=rw
FileAttribute> attr = PosixFilePermissions.asFileAttribute(perms);
Files.createFile(target, attr);
注意:父目錄權限遮罩可能限制實際權限(如 umask 導致 rw-rw-rw- 實際為 rw-r--r--)。
Path target = Paths.get("D:/Backup/MyStuff.txt");
Files.delete(target); // 不存在拋 NoSuchFileException
// 安全刪除:不存在不拋異常
Files.deleteIfExists(target);
Path source = Paths.get("C:/My Documents/Stuff.txt");
Path target = Paths.get("D:/Backup/MyStuff.txt");
Files.copy(source, target); // 目標存在拋 FileAlreadyExistsException
import static java.nio.file.StandardCopyOption.*;
Files.copy(source, target, REPLACE_EXISTING); // 覆蓋現有
Files.copy(source, target, COPY_ATTRIBUTES); // 保留屬性(時間、權限等)
Files.copy(source, target, REPLACE_EXISTING, COPY_ATTRIBUTES); // 組合
Path source = Paths.get("C:/My Documents/Stuff.txt");
Path target = Paths.get("D:/Backup/MyStuff.txt");
// 基本移動(同檔案系統相當於重命名,跨檔案系統為複製+刪除)
Files.move(source, target);
// 帶選項
Files.move(source, target, REPLACE_EXISTING, COPY_ATTRIBUTES, ATOMIC_MOVE);
選項詳解:
REPLACE_EXISTING:目標存在時覆蓋。COPY_ATTRIBUTES:盡可能複製文件屬性。ATOMIC_MOVE:原子性移動(同檔案系統下保證不可中斷,失敗回滾)。
Path p = Paths.get("/home/user/docs/report.txt");
p.getFileName(); // report.txt
p.getParent(); // /home/user/docs
p.getRoot(); // /
p.subpath(0, 2); // home/user (相對路徑片段)
p.toAbsolutePath(); // 絕對路御
p.toRealPath(); // 解析符號鏈接
p.resolve("backup"); // /home/user/docs/report.txt/backup
p.relativize(Paths.get("/home/user/photos")); // ../../photos
| 異常 | 觸發場景 | 處理建議 |
|---|---|---|
| NoSuchFileException | 源文件不存在 | 預先檢查 Files.exists() 或 try-catch |
| FileAlreadyExistsException | 目標存在且無 REPLACE_EXISTING | 加選項或先刪除 |
| DirectoryNotEmptyException | 刪除非空目錄 | 用 Files.walkFileTree 遞歸刪除 |
| AccessDeniedException | 權限不足 | 檢查應用權限、以管理員運行 |
| AtomicMoveNotSupportedException | 跨檔案系統用 ATOMIC_MOVE | 移除 ATOMIC_MOVE 或確保同檔案系統 |
| 舊 java.io.File | 新 java.nio.file |
|---|---|
| new File(path) | Paths.get(path) |
| file.exists() | Files.exists(path) |
| file.delete() | Files.delete(path) |
| file.renameTo(dest) | Files.move(src, dest, REPLACE_EXISTING) |
| file.mkdirs() | Files.createDirectories(path) |
| file.listFiles() | Files.newDirectoryStream(path) / Files.walk(path) |
| file.length() | Files.size(path) |
| file.lastModified() | Files.getLastModifiedTime(path) |
NIO.2 Files + Path 提供更豐富語義、更佳異常資訊、原子操作、屬性保留、流式目錄遍歷。新專案全面遷移,舊專案漸進式替換。