简体   繁体   English

如何关闭java.util.Stream并使用终端操作

[英]How to close a java.util.Stream and use a terminal operation

If I have a java.util.Stream that needs to be closed (once it's finished with), how can I both close it (by calling close ) and call a terminal operation such as count or collect ? 如果我有一个需要关闭(一旦完成)的java.util.Stream ,我该如何关闭(通过调用close )并调用诸如countcollect的终端操作?

For example: 例如:

java.nio.file.Files.lines(FileSystems.getDefault().getPath("myfile.txt"))
        .collect(Collectors.toSet());
        //.close(); ???

(in this example calling close isn't critical, but let's say I have a Stream object with a critical close operation registered on the stream via onClose). (在此示例中,调用close并不重要,但可以说我有一个Stream对象,该对象通过onClose在流中注册了关键的close操作)。

I guess you can store the stream in a temp var and close it, like this: 我猜您可以将流存储在temp var中并关闭它,如下所示:

Stream<String> ss = java.nio.file.Files.lines(FileSystems.getDefault().getPath("myfile.txt"));
Set<String> lines = ss.collect(Collectors.toSet());
ss.close();
return lines;

but it seems a bit clunky. 但似乎有点笨拙。 Is it always safe to close a stream in this fashion? 以这种方式关闭流是否总是安全的?

See docs. 参见文档。

8 8

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. 如果需要及时处理文件系统资源,则应使用try-with-resources构造来确保在流操作完成之后调用流的close方法。

12 12

This method must be used within a try-with-resources statement or similar control structure to ensure that the stream's open file is closed promptly after the stream's operations have completed. 必须在try-with-resources语句或类似的控制结构中使用此方法,以确保在流的操作完成后立即关闭流的打开文件。

I think you might want to consider using a try-with-resources construct. 我认为您可能要考虑使用try-with-resources构造。 Especially as the current one has evolved into "must". 特别是随着当前的发展成为“必须”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM