首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 7 NIO.2 文件操作完全指南:創建、刪除、複製、移動與屬性設置

     編輯:Java 相關知識

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 若已存在

帶 POSIX 權限創建(Linux/Unix/macOS)


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 核心操作補充


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

六、常見異常與處理

七、舊 API 遷移對照表

異常觸發場景處理建議
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 提供更豐富語義、更佳異常資訊、原子操作、屬性保留、流式目錄遍歷。新專案全面遷移,舊專案漸進式替換。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved