2

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

0

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Additionally, the code can be improved by not dealing with File.separator manually and using + instead of concat, i.e. Paths.get(nasProps.getUpstreamOutputDirectory(), inputSource + "_" + contentGroup + "_" + parentId). Further, the test .matches(".*\\." + extTxt) looks very much like the intended operation is .endsWith("." + extTxt).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.