使用 try-with-resources 或在 "finally" 子句中关闭此 "Stream"

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

我无法在 code/method 的这一行应用 Sonarqube 扫描建议的方法。

Sonarqube 说,“使用 try-with-resources 或在“finally”子句中关闭此“流”。”

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

非常感谢任何帮助!

您需要这样做:

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