The Java APIs describe this question as follows:
Streams have a BaseStream.close() method and implement AutoCloseable , but almost all stream instances do not actually need to be closed after use. As a rule, only streams whose source is an I / O channel (for example, those returned by Files.lines(Path, Charset)) ) need to be closed. Most threads are supported by collections, arrays, or generation functions that do not require special resource management. (If a thread requires closure, it can be declared as a resource in the try-with-resources statement.)
Also pay attention to the API for Files.lines(Path, Charset)) :
The returned stream encapsulates a Reader. If timely removal of file system resources is required, the try-with-resources construct should be used to ensure that the stream close method is called after stream operations have completed.
Bottom line: if a stream corresponds to a resource that should be closed in normal scripts after use (for example, IO), use it in the try-with-resources statement.
source share