本文介绍了为什么Files.lines(和类似的Streams)不会自动关闭?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Stream的javadoc状态:

The javadoc for Stream states:

因此,在绝大多数情况下,可以在单行中使用Streams,例如 collection.stream()。forEach(System.out :: println); 但是对于 Files.lines 和其他资源支持的流,必须使用try-with-resources语句或泄漏资源。

Therefore, the vast majority of the time one can use Streams in a one-liner, like collection.stream().forEach(System.out::println); but for Files.lines and other resource-backed streams, one must use a try-with-resources statement or else leak resources.

这让我觉得容易出错并且不必要。由于Streams只能迭代一次,在我看来,没有一个情况, Files.lines 的输出不应该在迭代后立即关闭,因此,实现应该在任何终端操作结束时隐式调用close。我错了吗?

This strikes me as error-prone and unnecessary. As Streams can only be iterated once, it seems to me that there is no a situation where the output of Files.lines should not be closed as soon as it has been iterated, and therefore the implementation should simply call close implicitly at the end of any terminal operation. Am I mistaken?

推荐答案

是的,这是一个深思熟虑的决定。我们考虑了两种选择。

Yes, this was a deliberate decision. We considered both alternatives.

这里的操作设计原则是获取资源的人应该释放资源。阅读EOF时文件不会自动关闭;我们希望打开文件的人明确关闭文件。由IO资源支持的流是相同的。

The operating design principle here is "whoever acquires the resource should release the resource". Files don't auto-close when you read to EOF; we expect files to be closed explicitly by whoever opened them. Streams that are backed by IO resources are the same.

幸运的是,该语言提供了一种为您自动执行此操作的机制:try-with-resources。因为Stream实现了AutoCloseable,你可以这样做:

Fortunately, the language provides a mechanism for automating this for you: try-with-resources. Because Stream implements AutoCloseable, you can do:

try (Stream<String> s = Files.lines(...)) {
    s.forEach(...);
}

自动关闭真的很方便,所以我可以把它写成一个单行很好,但主要是摇尾巴的尾巴。如果您打开了文件或其他资源,您还应该准备关闭它。有效和一致的资源管理胜过我想在一行中写下这一点,我们选择不扭曲设计只是为了保持一线性。

The argument that "it would be really convenient to auto-close so I could write it as a one-liner" is nice, but would mostly be the tail wagging the dog. If you opened a file or other resource, you should also be prepared to close it. Effective and consistent resource management trumps "I want to write this in one line", and we chose not to distort the design just to preserve the one-line-ness.

这篇关于为什么Files.lines(和类似的Streams)不会自动关闭?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 14:33
查看更多