【发布时间】:2022-02-07 19:18:06
【问题描述】:
我正在使用 Files.walk() 从目录中获取一些文件,但我收到了一个关于来自 sonarqube 和 sonarlint 的阻止程序错误的警告em> 代码分析那个
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;
我读了这个post 并且几乎遇到了问题,但我不知道我是如何将流停止在正确的位置。当我添加 finally 块时,它仍然给出同样的错误
try {
Files.walk(Paths.get(ifRecordsPath))
.filter(Files::isDirectory)
.map(ifRecordsCollector)
.map(ifRecordStreamAccumulator)
.forEach(ifRecordCollection::addAll);
} finally {
Files.walk(Paths.get(ifRecordsPath)).close();
}
我该如何解决这个问题?
【问题讨论】:
-
方法调用不是变量!如果您调用
Files.walk(Paths.get(ifRecordsPath))两次,您将创建两个不同的流。 -
你的代码在finally中创建了一个new流来关闭,你需要关闭原来的流。
标签: java spring java-stream try-catch-finally try-with-resources