声纳扫描显示关闭流,但没有要关闭的流
Sonar scan says close stream, but there is no stream to close
我有这个代码:
String requestedFile = Paths.get(prefix, name).toString();
// Find all matching files
List<String> foundFiles;
try {
foundFiles = Files.walk(Paths.get(PACKAGE_BASE), 1).filter(subdirectory -> Paths.get(subdirectory.toString(), requestedFile).toFile().exists()).map(String::valueOf).collect(Collectors.toList());
// Maybe we didn't find anything?
if (foundFiles.isEmpty()) return null;
String matchingFile = Paths.get(foundFiles.get(0), requestedFile).toString();
return matchingFile;
} catch (IOException e) {
return null;
}
我的声纳扫描显示:
Use try-with-resources or close this "Stream" in a "finally" clause
它发生在 Files.walk 调用中,但我没有编写这段代码,而且我不知道如何正确分解它以尝试使用资源或关闭流在最后。
有什么想法吗?
Stream<Path>
可关闭:
List<String> foundFiles;
try (Stream<Path> pathStream = Files.walk(Paths.get(PACKAGE_BASE), 1)) {
foundFiles = pathStream
.filter(subdirectory -> subdirectory.resolve(requestedFile).toFile().exists())
.map(String::valueOf)
.collect(Collectors.toList());
}
我有这个代码:
String requestedFile = Paths.get(prefix, name).toString();
// Find all matching files
List<String> foundFiles;
try {
foundFiles = Files.walk(Paths.get(PACKAGE_BASE), 1).filter(subdirectory -> Paths.get(subdirectory.toString(), requestedFile).toFile().exists()).map(String::valueOf).collect(Collectors.toList());
// Maybe we didn't find anything?
if (foundFiles.isEmpty()) return null;
String matchingFile = Paths.get(foundFiles.get(0), requestedFile).toString();
return matchingFile;
} catch (IOException e) {
return null;
}
我的声纳扫描显示:
Use try-with-resources or close this "Stream" in a "finally" clause
它发生在 Files.walk 调用中,但我没有编写这段代码,而且我不知道如何正确分解它以尝试使用资源或关闭流在最后。
有什么想法吗?
Stream<Path>
可关闭:
List<String> foundFiles;
try (Stream<Path> pathStream = Files.walk(Paths.get(PACKAGE_BASE), 1)) {
foundFiles = pathStream
.filter(subdirectory -> subdirectory.resolve(requestedFile).toFile().exists())
.map(String::valueOf)
.collect(Collectors.toList());
}