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

问题描述

考虑以下代码:

Path directory = Paths.get(/* some directory */);
Files.list(directory).forEach(System.out::println);

终端操作(如 forEach )关闭已打开的基础文件?

Does a terminal operation (like forEach) close the underlying file that has been opened?

请参阅:

如果它没有调用 Stream.close(),那会是什么?然后是生成可维护代码时调用它的最佳替代方法?

If it doesn't call Stream.close(), what would then be the best alternative to call it while producing maintainable code?

推荐答案

终端运营商不会自动关闭流。考虑以下代码:

Terminal operators do NOT close the stream automatically. Consider this code:

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

这不打印关闭。

但是,以下打印已关闭:

However, the following does print "Closed":

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

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

So the best way to do it is to use the try-with-resources mechanism.

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

10-29 10:03