java - Sonar-使用 try-with-resources 或在 "Stream"子句 java8 流中关闭此 "finally"

标签 java file java-8 sonarqube try-with-resources

Sonar qube 给我以下错误

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

List<Path> paths = find(Paths.get(nasProps.getUpstreamOutputDirectory() + File.separator + inputSource.concat("_").concat(contentGroup).concat("_").concat(parentId)),
                MAX_VALUE, (filePath, fileAttr) -> fileAttr.isRegularFile() && filePath.getFileName().toString().matches(".*\\." + extTxt))
                .collect(toList());
paths.stream().forEach(path -> textFileQueue.add(path));

我对java8不太了解。你能帮我关闭流吗

最佳答案

假设这里findFiles.find ,应该对你有用的是

final Path startPath = Paths.get(nasProps.getUpstreamOutputDirectory() +
        File.separator +
        inputSource.concat("_").concat(contentGroup).concat("_").concat(parentId));
BiPredicate<Path, BasicFileAttributes> matcher = (filePath, fileAttr) ->
        fileAttr.isRegularFile() && filePath.getFileName().toString().matches(".*\\." + extTxt);

try (Stream<Path> pathStream = Files.find(startPath, Integer.MAX_VALUE, matcher)) {
    pathStream.forEach(path -> textFileQueue.add(path));
} catch (IOException e) {
    e.printStackTrace(); // handle or add to method calling this block
}

链接文档的API注释中也提到了sonarqube在这里发出警告的原因:

This method must be used within a try-with-resources statement or similar control structure to ensure that the stream's open directories are closed promptly after the stream's operations have completed.

关于java - Sonar-使用 try-with-resources 或在 "Stream"子句 java8 流中关闭此 "finally",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54695998/

相关文章:

java - 有什么方法可以从 Lambda 闭包中停止 Stream.generate 吗?

java - Kraken API - 签名无效

java - '使用 for 循环比较 ArrayList 的每个元素是否等于用户响应

java - 如何使我的 e4 swt 应用程序图标在 Mac Dock 中弹起

java - 迭代映射列表 (List<Map<Integer,String>>) 并查找特定值?

c++ - C++从文件中读取数据

css - 为什么绝对和相对定位在 Firefox 中不能按预期工作?

java-8 - 使用 Files.lines 修改文件

file - 去安装: add non-source files to built package

java - Spring Boot jackson java.time.Duration