gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 09:51:26 24 4
gpt4 key购买 nike

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com