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)
您应该将它与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)
在apiNote为Files.walk明确读取此:
Run Code Online (Sandbox Code Playgroud)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.