I am having trouble to apply the suggested method by Sonarqube scan in this line of code/method.
Sonarqube says, "Use try-with-resources or close this "Stream" in a "finally" clause."
Files.list(voucherDirectory)
@Override
public String getLastModifiedFile() {
Path voucherDirectory = Paths.get(vouchiDir);
Optional<Path> lastFilePath = Optional.empty();
try {
lastFilePath = Files.list(voucherDirectory)
.filter(f -> !Files.isDirectory(f))
.max(Comparator.comparingLong(f -> f.toFile()
.lastModified()));
} catch (IOException e) {
log.error(e.getMessage(), e);
}
if (lastFilePath.isPresent()) {
return lastFilePath.get().getFileName().toString();
}
return "none";
}
Any help is really appreciated!
You need to do this:
try (Stream<Path> list = Files.list(voucherDirectory)) {
lastFilePath = list
.filter(f -> !Files.isDirectory(f))
.max(Comparator.comparingLong(f -> f.toFile()
.lastModified()));
} catch (IOException e) {
log.error(e.getMessage(), e);
}