如何在Java中关闭隐式Stream?

时间:2019-01-08 16:42:26

标签: java java-8 java-stream try-with-resources

Files.walk是我应关闭的流之一,但是,如何用下面的代码关闭流?下面的代码有效吗?还是需要重写它才能访问流以将其关闭?

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

2 个答案:

答案 0 :(得分:7)

您应将它与try-with-resource一起使用,例如:

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

Files.walk apiNote明确显示为:

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.

答案 1 :(得分:1)

根据Files.walk method documentation

  

返回的流封装了一个或多个DirectoryStream。如果   需要及时处理文件系统资源,   应使用try-with-resources构造来确保   在执行流操作之后,调用流的close方法   完成。。在封闭流上操作将导致   IllegalStateException。

强调我的。