简体   繁体   中英

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 ?

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).

I guess you can store the stream in a temp var and close it, like this:

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

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.

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.

I think you might want to consider using a try-with-resources construct. Especially as the current one has evolved into "must".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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