避免 Java 8 Files.walk(..) 终止原因 ( java.nio.file.AccessDeniedException )

Avoid Java 8 Files.walk(..) termination cause of ( java.nio.file.AccessDeniedException )

我正在使用 Java 8 Files.walk(..) 来计算文件夹中包含的 .mp3 个文件及其中的所有文件夹。换句话说,我正在访问文件树的所有级别。

当我得到 java.nio.file.AccessDeniedExceptionStream 关闭,我不希望出现这种情况。我需要它来忽略或打印异常并继续对文件进行计数。下面是我使用的代码 :) :

   /**
     * Count files in a directory (including files in all sub
     * directories)
     * 
     * @param directory
     *        the directory to start in
     * @return the total number of files
     */
    public int countFiles(File dir) {
        if (dir.exists())
            try (Stream<Path> paths = Files.walk(Paths.get(dir.getPath()), FileVisitOption.FOLLOW_LINKS)) {
                return (int) paths.filter(path -> {

                    // i am using something different here but i changed
                    // it just for the purpose of Whosebug question                                
                    return path.toString().contains(".mp3");

                }).count();
            } catch (IOException ex) {
                //Main.logger.log(Level.WARNING, "", ex);
                ex.printStackTrace();
            }

        return 0;
    }

StackTrace of error:

java.io.UncheckedIOException: java.nio.file.AccessDeniedException: C:$Recycle.B
in\S-1-5-18
    at java.nio.file.FileTreeIterator.fetchNextIfNeeded(FileTreeIterator.java:88)
    at java.nio.file.FileTreeIterator.hasNext(FileTreeIterator.java:104)
    at java.util.Iterator.forEachRemaining(Iterator.java:115)
    at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.jav
a:1801)
    at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
    at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
    at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
    at java.util.stream.LongPipeline.reduce(LongPipeline.java:438)
    at java.util.stream.LongPipeline.sum(LongPipeline.java:396)
    at java.util.stream.ReferencePipeline.count(ReferencePipeline.java:526)
    at smartcontroller.SmartController$InputService.countFiles(SmartController.ja
va:2092)
...

Similar question , though not the same I need a Stream to be returned .

Working around access denied in a FileWalking Tree in Java7


回答

这是一个临时解决方案,可以改进为使用 Java 8 Streams 和 Lambdas。

int[] count = {0};
try {
    Files.walkFileTree(
            Paths.get(dir.getPath()), 
            new HashSet<FileVisitOption>(Arrays.asList(FileVisitOption.FOLLOW_LINKS)),
            Integer.MAX_VALUE, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) 
                        throws IOException {
                    System.out.printf("Visiting file %s\n", file);
                    ++count[0];
                    return FileVisitResult.CONTINUE;
                }
                
                @Override
                public FileVisitResult visitFileFailed(Path file, IOException e) 
                        throws IOException {
                    System.err.printf("Visiting failed for %s\n", file);
                    return FileVisitResult.SKIP_SUBTREE;
                }
                
                @Override
                public FileVisitResult preVisitDirectory(Path dir,
                                                         BasicFileAttributes attrs) 
                        throws IOException {
                    System.out.printf("About to visit directory %s\n", dir);
                    return FileVisitResult.CONTINUE;
                }
            });
} catch (IOException e) {
    // handle exception
}