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

时间:2017-05-16 16:37:51

标签: java nio

  

描述

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

当我java.nio.file.AccessDeniedException Stream关闭时,我不想要这种行为。我需要它来忽略或打印异常并继续计数文件。下面是我使用的代码:):

           /**
             * 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 StackOverFlow question                                
                            return path.toString().contains(".mp3");

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

                return 0;
            }
  

错误的StackTrace:

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$1.countFiles(SmartController.ja
va:2092)
...
  

类似的问题,虽然不一样,但我需要返回一个Stream

Working around access denied in a FileWalking Tree in Java7

1 个答案:

答案 0 :(得分:1)

答案

这是一个临时解决方案,可以使用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) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}