How to close implicit Stream in Java?

Viewed 433

Files.walk is one of the streams that I should close, however, how do I close the stream in code like below? Is the code below valid or do I need to rewrite it so I have access to the stream to close it?

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

You should use it with try-with-resource as:

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

The apiNote for the Files.walk explicitly reads this :

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.

According to the 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.

Emphasis mine.

Related