Sonar-Use try-with-resources or close this quot;Streamquot; in a quot;finallyquot; clause java8 stream(声纳-使用Try-with-Resources或在quot;Finallyquot;子句java8流中关闭此流(q;Streamquot;))
问题描述
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了解不多。您能帮我关闭这条流吗?
推荐答案
假设find这里是Files.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在这里出现警告的原因:
此方法必须在try-with-resources语句中使用,或者 类似的控制结构,以确保流的打开目录 在流的操作完成后立即关闭。
这篇关于声纳-使用Try-with-Resources或在";Finally";子句java8流中关闭此流(&q;Stream";)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:声纳-使用Try-with-Resources或在";Finally";子句java8流中关闭此流(&q;Stream";)
基础教程推荐
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
