shreya
shreya

Reputation: 95

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

Sonar qube is giving me the following error

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

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

I dont have much understanding of java8. could you please help me to close the stream

Upvotes: 2

Views: 3246

Answers (1)

Naman
Naman

Reputation: 32046

Assuming find here is Files.find, what should work for you is

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
}

The reason why sonarqube is warning here is mentioned in the API note of linked document as well:

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.

Upvotes: 2

Related Questions