我从几个帖子和文档中读到,流中的资源不会自动关闭。
Does collect operation on Stream close the stream and underlying resources?
Why is Files.lines (and similar Streams) not automatically closed?
但我想知道我是否有一个很好的方法来关闭来自中间操作的流中的资源。像下面的代码:
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);
}
}
}
为了避免IllegalStateException(类似“流已经关闭”),我认为我无法在名为mapper的lambda表达式中使用try-with-resources,但是何时是关闭流的好时机?