Why is Java 7 Files.walkFileTree throwing exception on encountering a tar file on remote drive

爱⌒轻易说出口 提交于 2019-11-29 05:36:05

Workaround for the problem at hand:

But implement a visitFileFailed and you should be ok.

public class MyFileVisitor extends SimpleFileVisitor<Path> {
    @Override
    public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
        if (file.toString().endsWith(".tar")) {
            return FileVisitResult.CONTINUE;
        }
        return super.visitFileFailed(file, exc);
    }
}

Update: If we look closer we can see that walkFileTree uses the Files.readAttributes which turns to the current provider in play: WindowsFileSystemProvider.readAttributes to determine if a path is a directory.

As someone mentioned in the comments I also dont think the fault is in the Java-implementation but the OS-native-call that returns the wrong attribute

If you wanted to do a workaround for this, one option would be to implement your own FileSystem that wraps the WindowsFileSystem implementation transparently, except readAttributes returns .tar-paths as file instead of dir.

Tar-archives could be seen as directory (bundle of files). You can prevent this error by implementing method preVisitDirectory in your visitor simply returning FileVisitResult.SKIP_SUBTREE for tar-archives:

public static class CountFiles
        extends SimpleFileVisitor<Path> {
    ...
    public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
             throws IOException {
        if (dir.toString().toLowerCase().endsWith(".tar")) {
            return SKIP_SUBTREE;
        }
        return super.preVisitDirectory(dir, attrs);
    }
    ...
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!