为什么在try-with-resources中获取`Stream< String>`时BufferedReader没有关闭? [英] Why is BufferedReader not closed when obtaining `Stream<String>` in try-with-resources?

查看:214
本文介绍了为什么在try-with-resources中获取`Stream< String>`时BufferedReader没有关闭?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在try-with-resources中使用 Stream 时,应关闭阅读器。

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

给定这个:

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??

此测试失败:

    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());


推荐答案

我实际上并没有使用try-resources语法。希望我的回答是有道理的。

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.

因此,尝试(Stream< String> lines = new BufferedReader(r).lines()){只是关闭,但不是那个没有分配变量的缓冲读者。

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

如果你打算关闭缓冲的阅读器和流(你真的吗?)需要关闭流吗?),iirc,你可以在try语句中有多行:

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()) {
    //....
}

这样的事情。 (没有尝试编译,希望它有效:P)

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

这篇关于为什么在try-with-resources中获取`Stream&lt; String&gt;`时BufferedReader没有关闭?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆