在 Java 中遍歷目錄並按名稱規則過濾文件是常見需求。本文通過一個完整示例,講解 File.list()、startsWith()、endsWith()、contains() 組合實現多條件文件搜尋,並重點剖析路徑拼接陷阱。
import java.io.File;
import java.io.FileNotFoundException;
public class SearchFile {
public static void main(String[] args) throws FileNotFoundException {
// 1. 指定搜尋根目錄 (此處為 F 盤根目錄)
File dir = new File("F:/");
// 2. 獲取目錄下所有文件/子目錄名稱字符串數組
String[] names = dir.list();
if (names == null) {
System.out.println("目錄不存在或無讀取權限");
return;
}
// 3. 遍歷過濾
for (String name : names) {
// 條件 1:文件名以 "ja" 開頭 (前綴匹配)
boolean isPrefixMatch = name.startsWith("ja");
// 條件 2:必須是文件而非目錄 (關鍵:需用絕對路徑構建 File 對象)
File file = new File(dir.getAbsolutePath() + File.separator + name);
boolean isFile = file.isFile();
// 條件 3:文件名包含 "va" (關鍵字匹配)
boolean containsKeyword = name.contains("va");
// 組合條件:根據業務靈活調整
if (isPrefixMatch && isFile && containsKeyword) {
System.out.println("匹配文件:" + name);
}
}
}
}
File.list() vs File.listFiles()list():返回 String[],僅文件名,**不含路徑**,輕量但後續需自行拼接路徑判斷類型。listFiles():返回 File[],直接拿到文件對象,可直接調用 isFile()、isDirectory(),**推薦實戰使用**。File.separator 與 getAbsolutePath()原代碼第 11 行:
boolean b = (new File(files.getAbsolutePath() + s)).isFile();
錯誤寫法: new File(s).isFile()
原因: new File("相對路徑") 會相對於**當前工作目錄**(通常是專案根目錄)解析,而非目標目錄 F:\。若專案目錄無同名文件,永遠返回 false。
正確姿勢:
File target = new File(dir.getAbsolutePath() + File.separator + name); // 或 Java 7+ 推薦 Path target = Paths.get(dir.toURI()).resolve(name); boolean isFile = target.toFile().isFile();
getAbsolutePath() 確保基準路徑絕對化。File.separator 自動適配 Windows (\) 與 Linux (/) 分隔符,跨平台無憂。| 方法 | 用途 | 示例 | 大小寫敏感 |
|---|---|---|---|
startsWith(prefix) | 前綴匹配 | "java.txt".startsWith("ja") // true | 是 |
endsWith(suffix) | 後綴匹配 (如副檔名) | "data.csv".endsWith(".csv") // true | 是 |
contains(substr) | 包含關鍵字 | "report.pdf".contains("port") // true | 是 |
matches(regex) | 正則表達式 | "img001.jpg".matches("img\\d+\\.jpg") // true | 是 |