I investigate java nio2 possibilities.
I knew that I can search files using FileVisitor
interface. To achieve this functionality I use glob pattern.
code of my example:
visitor interface realization:
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;
}
}
main method:
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();
}
}
This variant of main method works properly but if I change:
Path startPath = Paths.get("E:\\folder");
with
Path startPath = Paths.get("E:\\");
I see following stacktrace:
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)
I don't the cause of this problem.
How to solve it?