另一种选择是使用 JDK7 中引入的 FileVisitor 接口来执行搜索。http://docs.oracle.com/javase/tutorial/essential/io/walk.html上的链接提供了有关如何使用 FileVisitor 界面的详细信息。
以下代码块是搜索的重新实现,除了普通目录之外,它还应该能够在 Windows 驱动器级别列出文件。请注意,该实现使用作为 NIO 2 文件 IO 操作的一部分提供的 Files.walkTree 方法。
public class FileSearch {
static String fd;
static boolean flg = true;
static class FileSearchVisitor extends SimpleFileVisitor<Path> {
private final Path pathToSearch;
boolean found;
FileSearchVisitor(Path pathToSearch) {
found = false;
this.pathToSearch = pathToSearch;
}
public boolean isFound() {
return found;
}
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
super.preVisitDirectory(dir, attrs);
if (pathToSearch.getFileName().equals(dir.getFileName())) {
System.out.println("Found " + pathToSearch);
found = true;
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
super.visitFile(file, attrs);
if (pathToSearch.getFileName().equals(file.getFileName())) {
System.out.println("Found " + pathToSearch);
found = true;
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) {
System.err.println("Visit failed for file at path : " + file);
exc.printStackTrace();
return FileVisitResult.CONTINUE;
}
}
public static void main(String arr[]) throws Exception {
fd = arr[0];
String path = arr[1];
final Path searchFile = Paths.get(fd);
Path filePath = Paths.get(path);
FileSearchVisitor visitor = new FileSearchVisitor(searchFile);
Files.walkFileTree(filePath, visitor);
if (!visitor.isFound()) {
System.out.print("File not found.");
}
}
}