如何关闭 Java 中的隐式流?

How to close implicit Stream in Java?

Files.walk 是我应该关闭的流之一,但是,如何在如下代码中关闭流?下面的代码是否有效,或者我是否需要重写它以便我可以访问流以关闭它?

List<Path> filesList = Files.walk(Paths.get(path)).filter(Files::isRegularFile ).collect(Collectors.toList());

根据 Files.walk method documentation:

The returned stream encapsulates one or more DirectoryStreams. If timely disposal of file system resources is required, the try-with-resources construct should be used to ensure that the stream's close method is invoked after the stream operations are completed. Operating on a closed stream will result in an IllegalStateException.

强调我的。

您应该将它与 try-with-resource 一起使用,如下所示:

try(Stream<Path> path = Files.walk(Paths.get(""))) {
    List<Path> fileList = path.filter(Files::isRegularFile)
                               .collect(Collectors.toList());
}

Files.walkapiNote 明确显示为:

This method must be used within a try-with-resources statement or similar
control structure to ensure that the stream's open directories are closed
promptly after the stream's operations have completed.