在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