-1

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?

jon hanson
  • 8,722
  • 2
  • 37
  • 61
  • You could just do `new HashSet(Files.readAllLines(Paths.get("myfile.txt")))`, and forego the Stream entirely. – VGR Aug 14 '19 at 15:51
  • @NathanHughes I rarely assign streams to variables. As per my first example the stream is created, used, and discarded. Try-with-resources implies assigning the stream to a variable. My question is whether that's the only way to close a stream, regardless of whether you use t-w-r. – jon hanson Aug 14 '19 at 15:52
  • @VGR `Files.readAllLines` is just one example of a stream that needs to be closed. My question pertains to any such stream. – jon hanson Aug 14 '19 at 15:53
  • 2
    Fair enough. To answer your question: No, it is not possible to close a Stream or any other AutoCloseable without either placing it in a try-with-resources statement, or assigning it to a variable. – VGR Aug 14 '19 at 15:54
  • 2
    Highly related (and possible duplicate): https://stackoverflow.com/questions/34072035/why-is-files-lines-and-similar-streams-not-automatically-closed (with a some good answers as to why it is like that). – Klitos Kyriacou Aug 14 '19 at 16:11
  • @KlitosKyriacou Thanks, Brian's explanation does make sense and trumps my sense of "it doesn't feel right". – jon hanson Aug 14 '19 at 17:40

1 Answers1

5

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

tevemadar
  • 12,389
  • 3
  • 21
  • 49