在Stream上收集操作是否关闭流和底层资源? [英] Does collect operation on Stream close the stream and underlying resources?

查看:152
本文介绍了在Stream上收集操作是否关闭流和底层资源?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码需要用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());


推荐答案


返回的流封装了一个 Reader 。如果需要及时处理文件
的系统资源,那么 try-with-resources 构造应该使用
来确保流的close方法被调用在
流操作完成之后。

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.

所以是的,包装 Stream try-with-resources 语句中由返回的$ c> (或关闭)。

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

这篇关于在Stream上收集操作是否关闭流和底层资源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆