使用try-with-resources时需要flush()调用 [英] Is flush() call necessary when using try-with-resources

查看:614
本文介绍了使用try-with-resources时需要flush()调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试使用资源隐式调用 flush()

如果是,在以下代码片段中, bw.flush()可以安全删除吗?

If it does, in the following code snippet, bw.flush() can be safely removed?

static void printToFile1(String text, File file) {
    try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) {
        bw.write(text);
        bw.flush();
    } catch (IOException ex) {
        // handle ex
    }
}

ps。
我在官方文件中没有看到任何关于它的描述:

ps. I don't see any description about it in official document:

https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
https://docs.oracle.com/javase/8/docs/api/java/lang/Au​​toCloseable.html

推荐答案

可关闭 AutoCloseable 是通用接口,对刷新一无所知。所以你在他们的文档中找不到任何关于它的信息 - 除了关于释放资源的一些话

A Writer 另一方面是更具体的抽象类,现在知道有关刷新的东西。 方法文档的一些摘录Writer.close()


关闭流,首先刷新

所以 - 是的 - 当使用作家时,关闭将始终 flush 。这基本上意味着你必须在试图找出结束真正做的事情时查阅你正在使用的具体类的文档。

So - yes - when using a writer, a close will always also flush. This basically means that you have to consult the documentation of the concrete classes that you are using when trying to find out what closing really does.

这篇关于使用try-with-resources时需要flush()调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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