Java 声纳使用-尝试使用资源或关闭此“;溪流;在“a”中;最后";第8条流

Java 声纳使用-尝试使用资源或关闭此“;溪流;在“a”中;最后";第8条流,java,file,java-8,sonarqube,try-with-resources,Java,File,Java 8,Sonarqube,Try With Resources,Sonar qube告诉我以下错误 使用try with resources或在“finally”子句中关闭此“流” List path=find(path.get(nasProps.getupstreamoutput目录()+File.separator+inputSource.concat(“”).concat(contentGroup.concat(“”).concat(parentId)), 最大值,(filePath,fileAttr)->fileAttr.isRegularFile(

Sonar qube告诉我以下错误

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

List path=find(path.get(nasProps.getupstreamoutput目录()+File.separator+inputSource.concat(“”).concat(contentGroup.concat(“”).concat(parentId)),
最大值,(filePath,fileAttr)->fileAttr.isRegularFile()&&filePath.getFileName().toString().matches(“.\\\.”+extTxt))
.collect(toList());
path.stream().forEach(path->textFileQueue.add(path));

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

假设
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
}
final Path startPath=Path.get(nasProps.getupstreamoutput目录()+
文件分隔符+
inputSource.concat(“”).concat(contentGroup.concat(“”).concat(parentId));
双预测匹配器=(文件路径,文件属性)->
fileAttr.isRegularFile()&&filePath.getFileName().toString().matches(“.\\\”+extTxt);
try(Stream pathStream=Files.find(startPath,Integer.MAX_VALUE,matcher)){
forEach(路径->textFileQueue.add(路径));
}捕获(IOE异常){
e、 printStackTrace();//句柄或添加到调用此块的方法
}
sonarqube在此处发出警告的原因也在链接文档的API注释中提到:

此方法必须在try with resources语句或 类似的控制结构,以确保流的打开目录 在溪流运行完成后立即关闭


此外,可以通过不手动处理
File.separator
和使用
+
而不是
concat
,即
path.get(nasProps.getUpstreamOutputDirectory(),inputSource+“\u”+contentGroup+“\u”+parentId)
来改进代码。此外,测试
.matches(“.\\\.”+extTxt)
看起来非常像预期的操作是
.endsWith(“.”+extTxt)
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
}