如何在Java中关闭隐式Stream?

C J*_*C J 5 java java-8 try-with-resources java-stream

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

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

Nam*_*man 7

您应该将它与try-with-resource一起使用:

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

apiNoteFiles.walk明确读取此:

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.
Run Code Online (Sandbox Code Playgroud)

  • 谢谢@nullpointer.我希望Java提供了一种更好的方法,比如自动关闭隐式流,因为它们不再可访问. (2认同)
  • @CJ没有像“隐式流”这样的东西。这是使用Files.walk方法的方法,该方法使流实例不可访问。 (2认同)