终端操作是否关闭流? [英] Do terminal operations close the stream?
问题描述
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.list
或 Files.创建).行
).它记录在 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屋!