流上的终端操作是否关闭源? [英] Do terminal operations on streams close the source?
问题描述
考虑以下代码:
Path directory = Paths.get(/* some directory */);
Files.list(directory).forEach(System.out::println);
终端操作(如 forEach
)关闭已打开的基础文件?
Does a terminal operation (like forEach
) close the underlying file that has been opened?
请参阅 Files.list :
返回的流封装了DirectoryStream。如果需要及时处理文件系统资源,则应使用try-with-resources构造来确保在流操作完成后调用流的close方法。
The returned stream encapsulates a DirectoryStream. 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.
如果它没有调用 Stream.close()
,那会是什么?然后是生成可维护代码时调用它的最佳替代方法?
If it doesn't call Stream.close()
, what would then be the best alternative to call it while producing maintainable code?
推荐答案
终端运营商不会自动关闭流。考虑以下代码:
Terminal operators do NOT close the stream automatically. Consider this code:
Stream<Path> list = Files.list(directory).onClose(() -> System.out.println("Closed"));
list.forEach(System.out::println);
这不打印关闭。
但是,以下打印已关闭:
However, the following does print "Closed":
try (Stream<Path> list = Files.list(directory).onClose(() -> System.out.println("Closed"))) {
list.forEach(System.out::println);
}
所以最好的方法是使用try-with-resources机制。
So the best way to do it is to use the try-with-resources mechanism.
这篇关于流上的终端操作是否关闭源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!