在Java程式中,如何在目錄中搜尋檔案?
以下範例顯示如何通過建立Filefiter
來搜尋目錄中的特定檔案。以下範例顯示檔案名以'D'
開頭的所有檔案。
package com.yiibai;
import java.io.*;
public class SearchFileInDirectory {
public static void main(String[] args) {
File dir = new File("F:/worksp/javaexamples/java_directories/src/com/yiibai");
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.startsWith("D");
}
};
String[] children = dir.list(filter);
if (children == null) {
System.out.println("Either dir does not exist or is not a directory: ");
} else {
for (int i = 0; i < children.length; i++) {
String filename = children[i];
System.out.println(filename);
}
}
}
}
執行上面範例程式碼,得到以下結果 -
DeleteDirectory.java
DirectoryHierarchy.java
DirectoryHierarchy2.java
DirectoryModificationTime.java
DirectoryModificationTime2.java
DirectorySize.java
DirectorySize2.java
DisplayRootDirectories.java