java - 在 lambda 表达式中捕获异常

标签 java java-8

我有使用 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)) 仍然会失败,并显示确切的堆栈跟踪信息。

最佳答案

要在递归目录遍历期间忽略错误,您需要使用带有 FileVisitorwalkFileTree执行错误处理。

基于流的便捷包装器 (walk) 会在遇到第一个错误时简单地终止,您无法阻止这种情况。

关于java - 在 lambda 表达式中捕获异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41659856/

相关文章:

java - 为应用程序中的单个 Tapestry 4 页面设置 ISO-8859-1 编码,否则完全是 UTF-8

java - 基本 Java MVC : Beans and associative entities with attributes

java - 通用compareTo类

java - 如何在vaadin中设置图像数据源

带有 Java 8 的 Tomcat 6 给出 JSP 编译错误

java - 为什么java 8使用默认方法而不是扩展方法

java - 是什么导致了 java.lang.ArrayIndexOutOfBoundsException 以及如何防止它?

java - 在 Java 中使用流初始化二维数组

java - Spring boot,JVM参数太多还是刚好够用?

java-8 - 到OffsetDateTime的日期字符串