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

Use try-with-resources or close this 'Stream' in a "finally" clause

我正在使用 Files.walk() 从目录中获取一些文件,但是我从 sonarqube[= 收到有关阻止程序错误的警告27=]和sonarlint代码分析

Connections, streams, files, and other classes that implement the Closeable interface or its super-interface, AutoCloseable, needs to be closed after use. Further, that close call must be made in a finally block otherwise an exception could keep the call from being made. Preferably, when class implements AutoCloseable, resource should be created using "try-with-resources" pattern and will be closed automatically.

代码如下:

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

        return ifRecordCollection;

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

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

我该如何解决这个问题?

意思是你需要将流保存到一个变量,然后在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;
}

或者这样:

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();
}