Why is BufferedReader not closed when obtaining `Stream<String>` in try-with-resources?

牧云@^-^@ 提交于 2019-12-10 21:27:43

问题


The reader should be closed when a Stream is used in a try-with-resources.

Given this:

try(Stream<String> lines = new BufferedReader(reader).lines()) {
            return lines.map(it -> trim ? it.trim() : it)
                    .collect(Collectors.toList());
}

... the reader is not being closed??

This test fails:

    AtomicBoolean closed = new AtomicBoolean(false);

    Reader r = new StringReader("  Line1 \n Line2") {

                @Override
                public void close() {
                    super.close();
                    closed.set(true);
                }

            };

    try(Stream<String> lines = new BufferedReader(r).lines()) {
            lines.map(it -> trim ? it.trim() : it)
                    .collect(Collectors.toList());
    }

    assertTrue("Reader was not closed.",closed.get());

回答1:


I haven't actually used try-resources syntax. Wish my answer makes sense.

From my understanding, auto-close is closing the resource declared at the statement, nothing else.

Therefore, try(Stream<String> lines = new BufferedReader(r).lines()) { is simply closing lines, but not that buffered reader that have no variable assigned.

If you are intended to close both the buffered reader and the stream (do you really need to close the stream anyway?), iirc, you can have multiple lines in the try statement:

try (BufferedReader br = new BufferedReader(r);
     Stream<String> lines = br.lines()) {
    //....
}

somethings like that. (Haven't tried to compile that, wish it works :P)



来源:https://stackoverflow.com/questions/20319417/why-is-bufferedreader-not-closed-when-obtaining-streamstring-in-try-with-res

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!