Java – does the terminal operation on the stream close the source?

See English answers > do terminal operations close the stream? two

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

Do terminal operations (like foreach) close open underlying files?

See files Relevant parts of Javadoc of list:

If you do not call stream Close (), the best way to generate maintainable code is to call it?

Solution

The terminal operator does not automatically close the stream Consider this Code:

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

This does not print "closed"

However, the following print as closed:

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

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

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>