我有使用 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))
仍然会失败,并显示确切的堆栈跟踪信息。
最佳答案
要在递归目录遍历期间忽略错误,您需要使用带有 FileVisitor 的 walkFileTree
执行错误处理。
基于流的便捷包装器 (walk
) 会在遇到第一个错误时简单地终止,您无法阻止这种情况。
关于java - 在 lambda 表达式中捕获异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41659856/