It is generally not necessary to close streams at all. You only need to close streams that use IO resources.
From the Stream documentation:
Streams have a
BaseStream.close()
method and implementAutoCloseable
, but nearly all stream instances do not actually need to be closed after use. Generally, only streams whose source is an IO channel (such as those returned byFiles.lines(Path, Charset)
) will require closing. Most streams are backed by collections, arrays, or generating functions, which require no special resource management. (If a stream does require closing, it can be declared as a resource in a try-with-resources statement.)
If you need to close a stream, then best practice would be to use the try-with-resources statement:
try ( Stream<String> stream = Files.lines(path, charset) ) {
// do something
}