因此,快速检查显示不会关闭:forEach
DirectoryStream
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.function.Consumer;
import java.util.stream.Stream;
/**
* Created for http://stackoverflow.com/q/27381329/1266906
*/
public class FileList {
public static void main(String[] args) {
Path directory = Paths.get("C:\\");
try {
Stream<Path> list = Files.list(directory).onClose(() -> System.out.println("Close called"));
list.forEach(System.out::println);
// Next Line throws "java.lang.IllegalStateException: stream has already been operated upon or closed" even though "Close called" was not printed
list.forEach(System.out::println);
} catch (IOException | IllegalStateException e) {
e.printStackTrace(); // TODO: implement catch
}
// The mentioned try-with-resources construct
try (Stream<Path> list = Files.list(directory)) {
list.forEach(System.out::println);
} catch (IOException | IllegalStateException e) {
e.printStackTrace(); // TODO: implement catch
}
// Own helper-method
try {
forEachThenClose(Files.list(directory), System.out::println);
} catch (IOException | IllegalStateException e) {
e.printStackTrace(); // TODO: implement catch
}
}
public static <T> void forEachThenClose(Stream<T> list, Consumer<T> action) {
try {
list.forEach(action);
} finally {
list.close();
}
}
}
我看到了两个提出的缓解措施:
- 使用 JavaDoc 中所述的 try-with-resources
Files.list
- 编写你自己的帮助程序方法,它利用了 final-block
哪个更易于维护可能取决于您需要多少个帮助程序方法。