Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to close implicit Stream in Java?

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());
like image 919
C J Avatar asked Jan 08 '19 16:01

C J


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.
like image 119
Naman Avatar answered Oct 12 '22 23:10

Naman


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.

like image 35
Ousmane D. Avatar answered Oct 13 '22 00:10

Ousmane D.