I read from several posts and docs that resources in a stream will not be closed automatically.
Does collect operation on Stream close the stream and underlying resources?
Why is Files.lines (and similar Streams) not automatically closed?
But I'm wondering if I have a nice way to close resources in a stream from intermediate operations. Like code below:
public class MyTest {
@Test
public void main() throws Exception {
test().forEach(System.out::println);
}
public List<String> test() throws Exception {
Path myPath = Paths.get(this.getClass().getClassLoader().getResource("test").toURI());
Function<Path, Stream<String>> mapper = path -> {
try {
return Files.lines(path, StandardCharsets.UTF_8);
} catch (IOException e) {
throw new UncheckedIOException("File cannot be read: " + path, e);
}
};
try {
return Files.list(myPath).peek(System.out::println)
.flatMap(mapper).peek(System.out::println)
.map(s -> s + " mapped").peek(System.out::println)
.collect(Collectors.toList());
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}
In order to avoid IllegalStateException(something like "stream is already closed"), I think I'm not able to use try-with-resources in the lambda expression named mapper, but when is the good timing to close the stream?