如何从中间操作中关闭流中的资源(Java 8)

时间:2016-12-02 08:46:54

标签: java java-8 java-stream

我从几个帖子和文档中读到,流中的资源不会自动关闭。

  1. Does collect operation on Stream close the stream and underlying resources?

  2. Why is Files.lines (and similar Streams) not automatically closed?

  3. 但我想知道我是否有一个很好的方法来关闭来自中间操作的流中的资源。像下面的代码:

    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,但是何时是关闭流的好时机?

0 个答案:

没有答案