mmaceachran
mmaceachran

Reputation: 3348

Sonar scan says close stream, but there is no stream to close

I have this code:

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;
}

My sonar scan is saying:

Use try-with-resources or close this "Stream" in a "finally" clause

It happens in the Files.walk call, but I did not write this code, and I don't know how to break this up properly to make it a try with resources, or get the stream to close in the finally.

Any Ideas?

Upvotes: 1

Views: 356

Answers (1)

wilx
wilx

Reputation: 18228

The Stream<Path> is closable:

    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());
    }

Upvotes: 4

Related Questions