我调查了 java nio2 的可能性。
我知道我可以使用FileVisitor
界面搜索文件。为了实现这个功能,我使用 glob 模式。
我的示例代码:
访客界面实现:
class MyFileFindVisitor extends SimpleFileVisitor<Path> {
private PathMatcher matcher;
public MyFileFindVisitor(String pattern){
try {
matcher = FileSystems.getDefault().getPathMatcher(pattern);
} catch(IllegalArgumentException iae) {
System.err.println("Invalid pattern; did you forget to prefix \"glob:\"? (as in glob:*.java)");
System.exit(1);
}
}
public FileVisitResult visitFile(Path path, BasicFileAttributes fileAttributes){
find(path);
return FileVisitResult.CONTINUE;
}
private void find(Path path) {
Path name = path.getFileName();
if(matcher.matches(name))
System.out.println("Matching file:" + path.getFileName());
}
public FileVisitResult preVisitDirectory(Path path, BasicFileAttributes fileAttributes){
find(path);
return FileVisitResult.CONTINUE;
}
}
主要方法:
public static void main(String[] args) {
Path startPath = Paths.get("E:\\folder");
String pattern = "glob:*";
try {
Files.walkFileTree(startPath, new MyFileFindVisitor(pattern));
System.out.println("File search completed!");
} catch (IOException e) {
e.printStackTrace();
}
}
main 方法的这种变体可以正常工作,但是如果我更改:
Path startPath = Paths.get("E:\\folder");
和
Path startPath = Paths.get("E:\\");
我看到以下堆栈跟踪:
Exception in thread "main" java.lang.NullPointerException
at sun.nio.fs.WindowsFileSystem$2.matches(WindowsFileSystem.java:312)
at io.nio.MyFileFindVisitor.find(FileTreeWalkFind.java:29)
at io.nio.MyFileFindVisitor.preVisitDirectory(FileTreeWalkFind.java:33)
at io.nio.MyFileFindVisitor.preVisitDirectory(FileTreeWalkFind.java:13)
at java.nio.file.FileTreeWalker.walk(FileTreeWalker.java:192)
at java.nio.file.FileTreeWalker.walk(FileTreeWalker.java:69)
at java.nio.file.Files.walkFileTree(Files.java:2600)
at java.nio.file.Files.walkFileTree(Files.java:2633)
at io.nio.FileTreeWalkFind.main(FileTreeWalkFind.java:42)
我不是这个问题的原因。
如何解决?