【问题标题】:Use try-with-resources or close this "Stream" in a "finally" clause使用 try-with-resources 或在“finally”子句中关闭此“Stream”
【发布时间】:2021-10-08 14:34:53
【问题描述】:

我无法在这行代码/方法中应用 Sonarqube 扫描建议的方法。

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

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

非常感谢任何帮助!

【问题讨论】:

    标签: java spring spring-boot sonarqube


    【解决方案1】:

    你需要这样做:

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

    【讨论】:

    • 如果我做对了,用这段代码替换 try 块应该可以解决问题,对吧? ?
    • 是的。只需用这个替换你的try
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-14
    • 2019-03-31
    • 1970-01-01
    • 2021-12-14
    • 2020-05-13
    • 2019-07-08
    • 1970-01-01
    相关资源
    最近更新 更多