使用 try-with-resources 或在“finally”子句中关闭此“Stream”

abi*_*kay 2 java spring try-catch-finally try-with-resources java-stream

我用来Files.walk()从目录中获取一些文件,但我从 Sonarqube 和 Sonarlint 代码分析中收到有关阻止程序错误的警告

连接、流、文件和其他实现 Closeable 接口或其超级接口 AutoCloseable 的类在使用后需要关闭。此外,该关闭调用必须在finally 块中进行,否则异常可能会导致调用无法进行。最好,当类实现 AutoCloseable 时,应使用“try-with-resources”模式创建资源并将自动关闭。

这是代码:

Files.walk(Paths.get(ifRecordsPath))
        .filter(Files::isDirectory)
        .map(ifRecordsCollector)
        .map(ifRecordStreamAccumulator)
        .forEach(ifRecordCollection::addAll);

return ifRecordCollection;
Run Code Online (Sandbox Code Playgroud)

我读了这篇文章,几乎遇到了问题,但我不知道如何准确地将流停止在正确的位置。当我添加finally块时,它仍然给出相同的错误

try {
    Files.walk(Paths.get(ifRecordsPath))
            .filter(Files::isDirectory)
            .map(ifRecordsCollector)
            .map(ifRecordStreamAccumulator)
            .forEach(ifRecordCollection::addAll);
} finally {
    Files.walk(Paths.get(ifRecordsPath)).close();
}
Run Code Online (Sandbox Code Playgroud)

我该如何解决这个问题?

Lin*_*ica 5

这意味着您需要将流保存到变量中,然后在 try-with-resources 中使用它或在 try-finally 中关闭它。所以要么这样:

try (Stream<Path> paths = Files.walk(Paths.get(ifRecordsPath))) {
    paths.filter(Files::isDirectory)
        .map(ifRecordsCollector)
        .map(ifRecordStreamAccumulator)
        .forEach(ifRecordCollection::addAll);
    return ifRecordCollection;
}
Run Code Online (Sandbox Code Playgroud)

或这个:

Stream<Path> paths = Files.walk(Paths.get(ifRecordsPath));
try {
    paths.filter(Files::isDirectory)
        .map(ifRecordsCollector)
        .map(ifRecordStreamAccumulator)
        .forEach(ifRecordCollection::addAll);
    return ifRecordCollection;
} finally {
    paths.close();
}
Run Code Online (Sandbox Code Playgroud)