我使用Files.walk有最简单的代码:
Stream<Path> stream = Files.walk(Paths.get("C:\\"));
stream.forEach(f -> {
System.out.println(f);
});
此代码抛出
Exception in thread "main" java.io.UncheckedIOException: java.nio.file.AccessDeniedException: C:\Documents and Settings
at java.nio.file.FileTreeIterator.fetchNextIfNeeded(Unknown Source)
at java.nio.file.FileTreeIterator.hasNext(Unknown Source)
at java.util.Iterator.forEachRemaining(Unknown Source)
at java.util.Spliterators$IteratorSpliterator.forEachRemaining (Unknown Source)
at java.util.stream.AbstractPipeline.copyInto(Unknown Source)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(Unknown
at java.util.stream.ForEachOps$ForEachOp.evaluateSequential (Unknown Source)
at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(Unknown Source)
at java.util.stream.AbstractPipeline.evaluate(Unknown Source)
at java.util.stream.ReferencePipeline.forEach(Unknown Source)
at devl.test.FindDuplicates.main(FindDuplicates.java:53)
Caused by: java.nio.file.AccessDeniedException: C:\Documents and Settings
at sun.nio.fs.WindowsException.translateToIOException(Unknown Source)
at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
at sun.nio.fs.WindowsDirectoryStream.<init>(Unknown Source)
at sun.nio.fs.WindowsFileSystemProvider.newDirectoryStream (Unknown Source)
at java.nio.file.Files.newDirectoryStream(Unknown Source)
at java.nio.file.FileTreeWalker.visit(Unknown Source)
at java.nio.file.FileTreeWalker.next(Unknown Source)
... 11 more
堆栈跟踪指向stream.forEach(f -> {
。在代码之前添加try / catch使其在抛出异常时停止读取文件。
问题是 - 我希望代码继续读取驱动器C上的不同文件,即使抛出异常。
似乎以某种方式在foreach中添加try / catch会解决它 - 我该怎么做(f -> {
上的try / catch,而不是System.out.println(f);
)?
请注意,我试图通过
来规避这一点Stream<Path> s = stream.filter(f -> !f.toFile().getAbsolutePath().contains("Documents and Setting"));
s.forEach(f -> {
但抛出相同的异常(即使stream.filter(f -> false)
失败)。
编辑:请注意,我不想重新抛出异常(like I was suggested)。因此,使用s.forEach(LambdaExceptionUtil.rethrowConsumer(System.out::println))
仍然会失败并显示堆栈跟踪。
答案 0 :(得分:4)
要在递归目录遍历期间忽略错误,您需要使用walkFileTree
和FileVisitor进行错误处理。
基于流的便利包装器(walk
)只是在他们遇到的第一个错误时终止,你无法阻止它。
答案 1 :(得分:0)
如果目录列表是您之后的目录,那么为什么不使用DirectoryStreamPaths呢?有关详情,请参阅此处的文档:https://docs.oracle.com/javase/7/docs/api/java/nio/file/DirectoryStream.html
另外,您可以将它与Java8结合使用,而且异常处理非常好。