java.io.File 不讀寫檔案內容,它代表路徑抽象,封裝了檔案/目錄的元數據操作:建立、刪除、重命名、屬性查詢、目錄遍歷。
| 類型 | 範例 | 說明 |
|---|---|---|
| 絕對路徑 | D:\\data\\a.txt / /home/user/a.txt | 從根目錄開始,唯一確定 |
| 相對路徑 | data\\a.txt / ./a.txt | 相對「當前工作目錄」 |
// Windows 建議雙反斜線或正斜線
File f1 = new File("D:\\data\\a.txt");
File f2 = new File("D:/data/a.txt"); // 推薦:跨平台通用
// 相對路徑:Eclipse 專案根目錄 / 控制台 class 檔所在目錄
File f3 = new File("data/a.txt");
// 父子路徑分離建構
File f4 = new File("D:/data", "a.txt"); // 等同 D:/data/a.txt
| 方法 | 返回值 | 作用 | 注意 |
|---|---|---|---|
| createNewFile() | boolean | 建立空檔案 | 父目錄必須存在,檔案已存回 false |
| mkdir() | boolean | 建立單層目錄 | 父目錄不存在失敗 |
| mkdirs() | boolean | 建立多層目錄 | 自動建立所有父目錄 |
| delete() | boolean | 刪除檔案/空目錄 | 非空目錄失敗 |
| exists() | boolean | 路徑是否存在 | |
| isFile() | boolean | 是否為檔案 | |
| isDirectory() | boolean | 是否為目錄 | |
| getName() | String | 檔案/目錄名 | 不含路徑 |
| getParent() | String | 父目錄路徑 | 無父目錄回 null |
| getAbsolutePath() | String | 絕對路徑 | 規範化後 |
| length() | long | 檔案大小 | 目錄回 0 |
| list() | String[] | 子項名稱陣列 | 非目錄回 null |
| listFiles() | File[] | 子項 File 陣列 | 非目錄回 null |
| renameTo(dest) | boolean | 重命名/移動 | 跨磁碟可能失敗 |
| setReadOnly() | boolean | 設為唯讀 | 不可逆(純 Java) |
File dir = new File("e:/Book");
File file = new File("e:/Book/chapter1.txt");
// 建立檔案
if (!file.exists()) file.createNewFile();
// 列出目錄內容
if (dir.isDirectory()) {
for (File f : dir.listFiles()) {
System.out.println(f.getName() + (f.isDirectory() ? "[目錄]" : " [" + f.length() + " bytes]"));
}
}
// 遞歸刪除目錄樹(慎用!)
public static void deleteAll(File f) {
if (f.isFile()) { f.delete(); return; }
for (File child : f.listFiles()) deleteAll(child);
f.delete(); // 最後刪除空目錄
}
public static void printTree(File root, String indent) {
System.out.println(indent + root.getName() + (root.isDirectory() ? "/" : ""));
if (root.isDirectory()) {
for (File child : root.listFiles()) {
printTree(child, indent + " ");
}
}
}
// 呼叫:printTree(new File("e:/Book"), "");
public static long getSize(File f) {
if (f.isFile()) return f.length();
long sum = 0;
for (File child : f.listFiles()) sum += getSize(child);
return sum;
}
File API 設計較老,缺陷:
現代替代: java.nio.file.Path + Files 工具類:
Path path = Paths.get("e:/Book/chapter1.txt");
Files.createDirectories(path.getParent()); // 等同 mkdirs
Files.deleteIfExists(path); // 不拋出例外
Files.copy(src, dest, StandardCopyOption.REPLACE_EXISTING);
Files.walkFileTree(root, new SimpleFileVisitor<>() { ... }); // 高效遍歷
File 適合簡單路徑操作、教學、舊專案維護。Path/Files:異常豐富、支援屬性/連結、Stream API 整合、效能更好。FileInputStream/Files.readAllBytes 等。