加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 流上的终端操作是否关闭源?

发布时间:2020-12-14 17:48:10 所属栏目:Java 来源:网络整理
导读:参见英文答案 Do terminal operations close the stream?2 请考虑以下代码: Path directory = Paths.get(/* some directory */);Files.list(directory).forEach(System.out::println); 终端操作(像forEach)是否关闭已打开的底层文件? 请参阅Files.list的ja
参见英文答案 > Do terminal operations close the stream?2
请考虑以下代码:
Path directory = Paths.get(/* some directory */);
Files.list(directory).forEach(System.out::println);

终端操作(像forEach)是否关闭已打开的底层文件?

请参阅Files.list的javadoc的相关部分:

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(),那么在生成可维护代码的时候,最好的方法就是调用它?

解决方法

终端操作符不会自动关闭流.考虑这个代码:
Stream<Path> list = Files.list(directory).onClose(() -> System.out.println("Closed"));
list.forEach(System.out::println);

这不打印“已关闭”.

但是,以下内容打印为“已关闭”:

try (Stream<Path> list = Files.list(directory).onClose(() -> System.out.println("Closed"))) {
    list.forEach(System.out::println);
}

所以最好的方法是使用try-with-resources机制.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读