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?