在 Java 8 流中捕获 UncheckedIOException

C-O*_*tto 5 java exception-handling exception java-stream

编辑:这似乎不可能,请参阅https://bugs.openjdk.java.net/browse/JDK-8039910。

我有一个帮助类,它提供了一个Stream<Path>. 这段代码只是Files.walk对输出进行包装和排序:

public Stream<Path> getPaths(Path path) {
    return Files.walk(path, FOLLOW_LINKS).sorted();
}
Run Code Online (Sandbox Code Playgroud)

由于遵循符号链接,如果文件系统中出现循环(例如 符号链接x -> .),则 中使用的代码Files.walk会抛出UncheckedIOException包装 的实例FileSystemLoopException。

在我的代码中,我想捕获此类异常,例如,只记录一条有用的消息。一旦发生这种情况,结果流可以/应该停止提供条目。

我尝试将.map(this::catchException)和添加.peek(this::catchException)到我的代码中,但在此阶段未捕获异常。

Path checkException(Path path) {
    try {
        logger.info("path.toString() {}", path.toString());
        return path;
    } catch (UncheckedIOException exception) {
        logger.error("YEAH");
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

如果有的话,我如何UncheckedIOException在我的代码中捕获 an发出 a Stream<Path>,以便路径的使用者不会遇到此异常?

例如,以下代码永远不会遇到异常:

List<Path> paths = getPaths().collect(toList());
Run Code Online (Sandbox Code Playgroud)

现在,异常是由代码调用触发的collect(我可以在那里捕获异常):

java.io.UncheckedIOException: java.nio.file.FileSystemLoopException: /tmp/junit5844257414812733938/selfloop

    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.java: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.ReferencePipeline.collect(ReferencePipeline.java:499)
    at ...
Run Code Online (Sandbox Code Playgroud)

编辑:我提供了一个简单的 JUnit 测试类。在这个问题中,我要求您通过修改provideStream.

package somewhere;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static java.nio.file.FileVisitOption.FOLLOW_LINKS;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.core.IsNot.not;
import static org.junit.Assert.fail;

public class StreamTest {
    @Rule
    public TemporaryFolder temporaryFolder = new TemporaryFolder();

    @Test
    public void test() throws Exception {
        Path rootPath = Paths.get(temporaryFolder.getRoot().getPath());
        createSelfloop();

        Stream<Path> stream = provideStream(rootPath);

        assertThat(stream.collect(Collectors.toList()), is(not(nullValue())));
    }

    private Stream<Path> provideStream(Path rootPath) throws IOException {
        return Files.walk(rootPath, FOLLOW_LINKS).sorted();
    }

    private void createSelfloop() throws IOException {
        String root = temporaryFolder.getRoot().getPath();
        try {
            Path symlink = Paths.get(root, "selfloop");
            Path target = Paths.get(root);
            Files.createSymbolicLink(symlink, target);
        } catch (UnsupportedOperationException x) {
            // Some file systems do not support symbolic links
            fail();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Hol*_*ger 3

你可以建造自己的步行流工厂:

\n\n
public class FileTree {\n    public static Stream<Path> walk(Path p) {\n        Stream<Path> s=Stream.of(p);\n        if(Files.isDirectory(p)) try {\n            DirectoryStream<Path> ds = Files.newDirectoryStream(p);\n            s=Stream.concat(s, StreamSupport.stream(ds.spliterator(), false)\n                .flatMap(FileTree::walk)\n                .onClose(()->{ try { ds.close(); } catch(IOException ex) {} }));\n        } catch(IOException ex) {}\n        return s;\n    }\n    // in case you don\xe2\x80\x99t want to ignore exceprions silently\n    public static Stream<Path> walk(Path p, BiConsumer<Path,IOException> handler) {\n        Stream<Path> s=Stream.of(p);\n        if(Files.isDirectory(p)) try {\n            DirectoryStream<Path> ds = Files.newDirectoryStream(p);\n            s=Stream.concat(s, StreamSupport.stream(ds.spliterator(), false)\n                .flatMap(sub -> walk(sub, handler))\n                .onClose(()->{ try { ds.close(); }\n                               catch(IOException ex) { handler.accept(p, ex); } }));\n        } catch(IOException ex) { handler.accept(p, ex); }\n        return s;\n    }\n    // and with depth limit\n    public static Stream<Path> walk(\n                  Path p, int maxDepth, BiConsumer<Path,IOException> handler) {\n        Stream<Path> s=Stream.of(p);\n        if(maxDepth>0 && Files.isDirectory(p)) try {\n            DirectoryStream<Path> ds = Files.newDirectoryStream(p);\n            s=Stream.concat(s, StreamSupport.stream(ds.spliterator(), false)\n                .flatMap(sub -> walk(sub, maxDepth-1, handler))\n                .onClose(()->{ try { ds.close(); }\n                               catch(IOException ex) { handler.accept(p, ex); } }));\n        } catch(IOException ex) { handler.accept(p, ex); }\n        return s;\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n