Does collect operation on Stream close the stream and underlying resources?

前端 未结 2 1198
萌比男神i
萌比男神i 2020-12-05 10:42

Does below code need to be wrapped in try-with-resources to make sure underlying file is closed?

List rows = Files.lines(inputFilePath).collect         


        
2条回答
  •  温柔的废话
    2020-12-05 11:20

    As the javadoc of the overloaded Files#lines(Path, Charset) method states

    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.

    So yes, wrap the Stream returned by lines in a try-with-resources statement. (Or close it appropriately.)

提交回复
热议问题