Sonar qube is giving me the following error:
Use try-with-resources or close this “Stream” in a “finally” clause
This is my code:
Path start = Paths.get(filePath); Stream<File> stream; try { stream = Files.walk(start, 1, FileVisitOption.FOLLOW_LINKS).map(s -> s.toFile()); List<File> files = stream.collect(Collectors.toList()); files.remove(0); for (File f : files) { String fileName = f.toPath().getFileName().toString(); if (fileName.matches(regex)) { fileList.add(f.toPath().toString()); } } } catch (IOException e) { }
How can I fix this error?
Advertisement
Answer
define and open your stream this way:
try (Stream<File> stream = Files.walk(start, 1, FileVisitOption.FOLLOW_LINKS).map(s -> s.toFile())){
Doing this, the system will automatically close the stream and you don’t need to worry about it