为什么 Java 7 Files.walkFileTree 在远程驱动器上遇到 tar 文件时会引发异常

2022-09-02 22:43:19

我用于导航文件夹并计算音频文件,但是当遇到tar文件时存在问题,它似乎将其视为实际文件夹,我希望它只是跳过它。Files.WalkFileTree()

我看不到任何可以让我控制此行为的选项

法典:

package com.jthink.songkong.fileloader;


import com.jthink.songkong.cmdline.SongKong;
import com.jthink.songkong.ui.MainWindow;

import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.concurrent.Callable;
import java.util.logging.Level;

/**
 * Count the number of files that can be loaded, for information purposes only
 */
public class CountFilesinFolder implements Callable<Boolean> {
    public static class CountFiles
            extends SimpleFileVisitor<Path> {
        private int fileCount = 0;
        private final PathMatcher matcher;

        CountFiles(String pattern) {
            matcher =
                    FileSystems.getDefault()
                            .getPathMatcher("regex:" + pattern);
        }

        /**
         * Find Music file
         *
         * @param file
         * @param attr
         * @return
         */
        @Override
        public FileVisitResult visitFile(Path file,
                                         BasicFileAttributes attr) {
            Path name = file.getFileName();
            if (name != null && matcher.matches(name)) {
                fileCount++;
            }
            return FileVisitResult.CONTINUE;
        }

        public int getFileCount() {
            return fileCount;
        }
    }


    private Path scanDir;
    public CountFilesinFolder(Path scanDir) {
        this.scanDir = scanDir;
    }

    public Boolean call() {
        CountFiles countFiles = null;
        try {
            countFiles = new CountFiles("^(?!._).*[.](?:mp3|mp4|m4p|m4b|m4a|ogg|flac|wma)$");
            Files.walkFileTree(scanDir, countFiles);
        }
        catch (Exception e) {
            MainWindow.logger.log(Level.SEVERE, "Unable to find file for deriving base folder", e);
        }
        MainWindow.logger.severe("Music File Count:"+countFiles.getFileCount());
        SongKong.setMaxProgress(countFiles.getFileCount());
        return true;
    }
}

给出此堆栈跟踪

java.nio.file.NoSuchFileException: Z:\Scratch\fred.tar
    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:526)
    at java.nio.file.Files.newDirectoryStream(Files.java:411)
    at java.nio.file.FileTreeWalker.walk(FileTreeWalker.java:179)
    at java.nio.file.FileTreeWalker.walk(FileTreeWalker.java:199)
    at java.nio.file.FileTreeWalker.walk(FileTreeWalker.java:69)
    at java.nio.file.Files.walkFileTree(Files.java:2591)
    at java.nio.file.Files.walkFileTree(Files.java:2624)
    at com.jthink.songkong.fileloader.CountFilesinFolder.call(CountFilesinFolder.java:68)
    at com.jthink.songkong.fileloader.CountFilesinFolder.call(CountFilesinFolder.java:15)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
    at java.util.concurrent.FutureTask.run(FutureTask.java:166)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
    at java.lang.Thread.run(Thread.java:722)

但那是一个远程驱动器(nas驱动器),我在本地驱动器上没有得到这样的错误

编辑实现了以下基于o下面的答案,我认为有效

    @Override
            public FileVisitResult preVisitDirectory(Path dir, 
BasicFileAttributes attrs)
                    throws IOException {
                if(dir.endsWith(".tar"))
                {
                    return FileVisitResult.SKIP_SUBTREE;
                }
                return super.preVisitDirectory(dir, attrs);
            }

但是我的测试不对,它实际上不起作用,因为FileTreeWalker中失败的代码是在previsit方法之前调用的。

try {
            DirectoryStream<Path> stream = null;
            FileVisitResult result;

            // open the directory
            try {
                stream = Files.newDirectoryStream(file);
            } catch (IOException x) {
                return visitor.visitFileFailed(file, x);
            } catch (SecurityException x) {
                // ignore, as per spec
                return FileVisitResult.CONTINUE;
            }

            // the exception notified to the postVisitDirectory method
            IOException ioe = null;

            // invoke preVisitDirectory and then visit each entry
            try {
                result = visitor.preVisitDirectory(file, attrs);
                if (result != FileVisitResult.CONTINUE) {
                    return result;
                }

答案 1

手头问题的解决方法:

但是实现访问文件失败,你应该没事。

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);
    }
}

更新:如果我们仔细观察,我们可以看到 walkFileTree 使用 Files.readAttributes,它转向当前正在播放的提供程序:WindowsFileSystemProvider.readAttributes 来确定路径是否是目录。

正如评论中提到的那样,我也不认为错误在于Java实现,而是返回错误属性的OS-native调用

如果要对此执行解决方法,一种选择是实现您自己的文件系统,以透明方式包装 WindowsFileSystem 实现,除了 readAttributes 将.tar路径作为文件而不是 dir 返回。


答案 2

推荐