Stream 上的 collect 操作是否会关闭流和底层资源? [英] Does collect operation on Stream close the stream and underlying resources?
问题描述
以下代码是否需要包含在 try-with-resources 中以确保关闭底层文件?
Does below code need to be wrapped in try-with-resources to make sure underlying file is closed?
List<String> rows = Files.lines(inputFilePath).collect(Collectors.toList());
推荐答案
作为重载的javadoc Files#lines(Path, Charset)
方法状态
As the javadoc of the overloaded Files#lines(Path, Charset)
method states
返回的流封装了一个Reader
.如果及时处理文件需要系统资源,try-with-resources
构造应该用于确保流的关闭方法在流操作完成.
The returned stream encapsulates a
Reader
. If timely disposal of file system resources is required, thetry-with-resources
construct should be used to ensure that the stream's close method is invoked after the stream operations are completed.
所以是的,将 lines
返回的 Stream
包装在 try-with-resources
语句中.(或关闭它.)
So yes, wrap the Stream
returned by lines
in a try-with-resources
statement. (Or close it appropriately.)
这篇关于Stream 上的 collect 操作是否会关闭流和底层资源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!