考虑这种Java方法:
private void printContents(final Path start) throws Exception {
System.out.println("Finding the contents of " + start);
Files.walkFileTree(start, new SimpleFileVisitor<Path>() {
@Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IllegalArgumentException {
System.out.println("preVisitDirectory: " + dir); // do this to indicate progress
return FileVisitResult.CONTINUE;
}
@Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IllegalArgumentException {
System.out.println("visitFile: file = " + file); // do this to indicate progress
return FileVisitResult.CONTINUE;
}
@Override public FileVisitResult visitFileFailed(Path file, IOException ioe) throws IOException {
System.out.println("visitFileFailed: file = " + file + ", ioe = " + ioe); // do this to indicate progress
throw ioe;
}
} );
}
它通常可以正常工作,打印出目录内容,几乎可以提供任何启动值。
但是假设start arg实际上是NTFS卷的根目录(例如像“G:”这样的驱动器号)并且假设卷是空的(即没有内容)。然后printContents使用此堆栈跟踪抛出NoSuchFileException:
java.nio.file.NoSuchFileException: G:
at sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:79)
at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:97)
at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:102)
at sun.nio.fs.WindowsDirectoryStream.<init>(WindowsDirectoryStream.java:86)
at sun.nio.fs.WindowsFileSystemProvider.newDirectoryStream(WindowsFileSystemProvider.java:518)
at java.nio.file.Files.newDirectoryStream(Files.java:457)
at java.nio.file.FileTreeWalker.visit(FileTreeWalker.java:300)
at java.nio.file.FileTreeWalker.walk(FileTreeWalker.java:322)
at java.nio.file.Files.walkFileTree(Files.java:2662)
at java.nio.file.Files.walkFileTree(Files.java:2742)
at FileTreeComparer.printContents(FileTreeComparer.java:457)
...
为什么会发生这种情况,是否有任何解决方法?
我注意到如果start arg是空FAT32卷的根目录,则不会产生任何问题。
此外,如果start arg是NTFS卷上根目录的某个子目录(例如G:\ tmp),那么无论是否为空,这也都不会产生任何问题。
不,问题似乎被隔离到空的NTFS根目录。