So a quick-check reveals that forEach
does not close the 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 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 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 void forEachThenClose(Stream list, Consumer action) {
try {
list.forEach(action);
} finally {
list.close();
}
}
}
I see the two presented mitigations:
- use try-with-resources as stated in the
Files.list
JavaDoc
- write your own helper-method which utilizes a finally-block
Which is more maintainable depends probably on how-many helper-methods you would need.