在 Java 開發中,java.io.File 類是處理文件系統操作的基石。它不僅能表示文件與目錄的路徑,還提供了豐富的方法來創建、刪除、判斷以及遍歷文件結構。本文將系統梳理 File 類的構造函數、常用方法,並通過完整代碼示例演示如何遞歸遍歷多層目錄結構。
File 類提供了四種構建方式,靈活適配不同場景:
File(String pathname):以路徑字符串創建對象,最常用方式File(URL url):基於 URL 對象創建,適用於網絡資源定位File(File parent, String child):父目錄 File 對象 + 子路徑字符串,路徑拼接更安全File(String parent, String child):父目錄路徑字符串 + 子路徑字符串\ 在 Java 字符串中需轉義為 \\,或統一使用正斜杠 /(跨平台兼容更好)。| 方法 | 功能說明 | 備註 |
|---|---|---|
exists() | 判斷文件/目錄是否存在 | 操作前必檢查 |
mkdir() | 創建單級目錄 | 父目錄不存在會失敗 |
mkdirs() | 創建多級目錄 | 會自動創建父目錄 |
createNewFile() | 創建新文件 | 拋 IOException,路徑不存在也會異常 |
delete() | 刪除文件/空目錄 | 非空目錄需先清空內容 |
isDirectory() | 判斷是否為目錄 | |
isFile() | 判斷是否為文件 | |
getAbsolutePath() | 獲取絕對路徑 | 規範化路徑表示 |
getName() | 獲取文件/目錄名稱 | 不含路徑 |
getParent() | 獲取父目錄路徑 | 可能返回 null |
list() | 獲取子項名稱數組 | 僅返回 String[],不遞歸 |
listFiles() | 獲取子項 File 對象數組 | 推薦使用,支持進一步操作 |
以下代碼演示如何從指定根目錄出發,遞歸打印所有層級的文件路徑:
import java.io.File;
import java.io.IOException;
public class DirectoryWalker {
public static void main(String[] args) {
// 建議使用正斜杠或雙反斜杠
File rootDir = new File("F:/documents/example");
listAllFiles(rootDir);
}
public static void listAllFiles(File dir) {
// 1. 參數合法性校驗
if (!dir.exists()) {
throw new IllegalArgumentException("目錄不存在:" + dir);
}
if (!dir.isDirectory()) {
throw new IllegalArgumentException("非目錄路徑:" + dir);
}
// 2. 獲取子項並空值防護
File[] children = dir.listFiles();
if (children == null || children.length == 0) {
return; // 空目錄或無權限讀取
}
// 3. 遞歸處理
for (File child : children) {
if (child.isDirectory()) {
listAllFiles(child); // 進入子目錄
} else {
System.out.println(child.getAbsolutePath()); // 打印文件完整路徑
}
}
}
}
SecurityException 處理無權限目錄。Files.walkFileTree (NIO.2) 替代遞歸,避免棧溢出。File.separator 常量,增強跨平台性。掌握 File 類的遍歷機制,是處理批量文件操作、項目資源掃描等場景的基礎技能。靈活運用遞歸與迭代,能高效解決複雜目錄結構的處理需求。