Video in progress
Do you have to close the Stream returned by Files.lines()? Doesn't it finish after the terminal operation?
Yes, you do. A terminal operation makes the stream "used up", but it does not call close(). Files.lines holds an open file that is released only when the stream is closed, so you need try-with-resources.
📖 Answer
Many people don't know this, because nobody closes list.stream(). The difference: a stream over an ordinary collection holds no resources, while Files.lines, Files.list, Files.walk and Files.find open a file or directory handle from the OS.
// leak: the file stays open
long errors = Files.lines(log).filter(l -> l.contains("ERROR")).count();
// correct
long errors;
try (Stream<String> lines = Files.lines(log)) {
errors = lines.filter(l -> l.contains("ERROR")).count();
}
The Javadoc says so explicitly: streams returned by these methods should be used inside try-with-resources.
IntelliJ warns about this too ("'Stream' used without try-with-resources"): don't ignore the yellow highlight.
On Windows there is another effect: a file left open can't be deleted or moved later. On Linux the delete works, but the disk space isn't freed until the descriptor is closed.
Sign up to mark studied questions and save your progress.