终端操作是否关闭流? [英] Do terminal operations close the stream?

查看:24
本文介绍了终端操作是否关闭流?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

dirPath 包含 200k 个文件.我想一一阅读并做一些处理.以下代码段导致 java.nio.file.FileSystemException: dirPath/file-N Too many open files.终端操作 forEach() 不是应该在移动到下一个之前关闭打开的流(即打开的文件)吗?换句话说,我是否必须为流式文件添加 try-with-resources?

dirPath contains 200k files. I want to read them one by one and do some processing. The following snippet causes java.nio.file.FileSystemException: dirPath/file-N Too many open files. Isn't the terminal operation forEach() supposed to close the open stream (i.e. the open file) before moving to the next one? In other words, do I have to add try-with-resources for the streamed files?

Files.list(dirPath)
     .forEach(filePath -> {
              Files.lines(filePath).forEach() { ... }
              });

推荐答案

No forEach 不会关闭流(由 Files.listFiles.创建).行).它记录在 javadoc 中,例如 Files.list:

No forEach does not close the stream (created by Files.list or Files.lines). It is documented in the javadoc, for example for Files.list:

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

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.

这篇关于终端操作是否关闭流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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