参见英文答案 >
Do terminal operations close the stream?2
请考虑以下代码:
请考虑以下代码:
Path directory = Paths.get(/* some directory */); Files.list(directory).forEach(System.out::println);
请参阅Files.list的javadoc的相关部分:
The returned stream encapsulates a DirectoryStream. 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.
解决方法
终端操作符不会自动关闭流.考虑这个代码:
Stream<Path> list = Files.list(directory).onClose(() -> System.out.println("Closed")); list.forEach(System.out::println);
这不打印“已关闭”.
try (Stream<Path> list = Files.list(directory).onClose(() -> System.out.println("Closed"))) { list.forEach(System.out::println); }
所以最好的方法是使用try-with-resources机制.