Java 流 Files.lines() 抛出 IOException。为什么?

Java Streams Files.lines() throws IOException. Why?

Files.lines() returns a Stream<String> 据我了解,除非我对其应用终端操作,否则不会对其进行评估。那么,为什么它声明一个 IOException。在 Stream 的初始化过程中可能会出现什么错误,这将证明异常声明是正确的?

我的用例是下面的方法。我想创建一个流,从目录中的所有文件中使用搜索模式流式传输所有文本行。

现在,如果 Files.lines() 在流评估期间遇到以意外编码格式化的文件,它将失败并出现运行时异常。该异常不会被 catch 块捕获。那么,为什么我需要异常处理呢?

public static Stream<String> grep(Path dir, Pattern pattern) throws IOException {
    return Files.walk(dir)
            .filter(p -> !Files.isDirectory(p) && p.getFileName().toString().endsWith(".log"))
            .map(p -> {
                try {
                    return Files.lines(p);
                } catch(Exception e) {
                    return Stream.<String>empty();
                }
            }).flatMap(s -> s)
            .filter(l -> pattern.matcher(l).find());
}

虽然在应用终端操作之前不会评估返回的流,但在 Files.lines 中创建流本身正在创建一个新的 Files.newBufferedReader,这可能会引发给定的异常。

我们可以在第 3744 行看到这个 - source

public static Stream<String> lines(Path path, Charset cs) throws IOException {
    BufferedReader br = Files.newBufferedReader(path, cs); // this could throw IOException
    try {
        return br.lines().onClose(asUncheckedRunnable(br));
    } catch (Error|RuntimeException e) {
        try {
            br.close();
        } catch (IOException ex) {
            try {
                e.addSuppressed(ex);
            } catch (Throwable ignore) {}
        }
        throw e;
    }
}