【问题标题】:Use try-with-resources or close this 'Stream' ini a "finally" clause [duplicate]使用 try-with-resources 或在“finally”子句中关闭此“Stream”[重复]
【发布时间】:2022-02-07 19:18:06
【问题描述】:

我正在使用 Files.walk() 从目录中获取一些文件,但我收到了一个关于来自 sonarqubesonarlint 的阻止程序错误的警告em> 代码分析那个

Connections, streams, files, and other classes that implement the Closeable interface or its super-interface, AutoCloseable, needs to be closed after use. Further, that close call must be made in a finally block otherwise an exception could keep the call from being made. Preferably, when class implements AutoCloseable, resource should be created using "try-with-resources" pattern and will be closed automatically.

代码如下:

Files.walk(Paths.get(ifRecordsPath))
                .filter(Files::isDirectory)
                .map(ifRecordsCollector)
                .map(ifRecordStreamAccumulator)
                .forEach(ifRecordCollection::addAll);

        return ifRecordCollection;

我读了这个post 并且几乎遇到了问题,但我不知道我是如何将流停止在正确的位置。当我添加 finally 块时,它仍然给出同样的错误

try {
            Files.walk(Paths.get(ifRecordsPath))
                    .filter(Files::isDirectory)
                    .map(ifRecordsCollector)
                    .map(ifRecordStreamAccumulator)
                    .forEach(ifRecordCollection::addAll);
        } finally {
            Files.walk(Paths.get(ifRecordsPath)).close();
        }

我该如何解决这个问题?

【问题讨论】:

  • 方法调用不是变量!如果您调用Files.walk(Paths.get(ifRecordsPath)) 两次,您将创建两个不同的流。
  • 你的代码在finally中创建了一个new流来关闭,你需要关闭原来的流。

标签: java spring java-stream try-catch-finally try-with-resources


【解决方案1】:

这意味着您需要将流保存到变量中,然后在 try-with-resources 中使用它或在 try-finally 中关闭它。所以要么这样:

try (Stream<Path> paths = Files.walk(Paths.get(ifRecordsPath))) {
    paths.filter(Files::isDirectory)
        .map(ifRecordsCollector)
        .map(ifRecordStreamAccumulator)
        .forEach(ifRecordCollection::addAll);
    return ifRecordCollection;
}

或者这个:

Stream<Path> paths = Files.walk(Paths.get(ifRecordsPath));
try {
    paths.filter(Files::isDirectory)
        .map(ifRecordsCollector)
        .map(ifRecordStreamAccumulator)
        .forEach(ifRecordCollection::addAll);
    return ifRecordCollection;
} finally {
    paths.close();
}

【讨论】:

    猜你喜欢
    • 2021-10-08
    • 2021-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-31
    • 2021-12-14
    • 2020-05-13
    • 2019-07-08
    相关资源
    最近更新 更多