Do terminal operations close the stream?
java-8, java-stream
Solution
No `forEach` does not close the stream (created by `Files.list` or `Files.lines`). It is documented in the javadoc, for example for `Files.list`:
The returned stream encapsulates a Reader. 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.
Problem
`dirPath` contains 200k files. I want to read them one by one and do some processing. The following snippet causes `java.nio.file.FileSystemException: dirPath/file-N Too many open files`. Isn't the terminal operation `forEach()` supposed to close the open stream (i.e. the open file) before moving to the next one? In other words, do I have to add try-with-resources for the streamed files? ``` Files.list(dirPath) .forEach(filePath -> { Files.lines(filePath).forEach() { ... } }); ```