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 implement AutoCloseable
, 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 by Files.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
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…