如何为PrintWriter使用flush() [英] How to use flush() for PrintWriter

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

问题描述

我有一些这样的代码:

PrintWriter pw = new PrintWriter(new BufferedReader(....));
for(int i=0; i<10; i++) {
    pw.println("a");
    pw.flush();// flush each time when println()?
}
pw.close();

每个'for'语句中的 flush()是否必然?我听说flush()会在调用 close()时自动调用。
如果我写这样的代码:

Is the flush() in each 'for' statement necessarily? I heard that flush() would auto invoke when invoke close() . If I write code like this:

PrintWriter pw = new PrintWriter(new BufferedReader(....), true);

我不会再写 pw.flush()了?谢谢。

推荐答案

flush() 可能是你的例子中不需要。

flush() is probably not required in your example.

它的作用是确保在调用 flush()之前写入编写器的任何内容写入基础流,而不是放在某个内部缓冲区中。

What it does is ensure that anything written to the writer prior to the call to flush() is written to the underlying stream, rather than sit in some internal buffer.

该方法在几种情况下派上用场:

The method comes in handy in several types of circumstances:


  1. 如果另一个进程(或线程)需要在写入文件时检查该文件,并且另一个进程看到所有最近的进程很重要写道。

  1. If another process (or thread) needs to examine the file while it's being written to, and it's important that the other process sees all the recent writes.

如果写入过程可能会崩溃,并且重要的是不会丢失对文件的写入。

If the writing process might crash, and it's important that no writes to the file get lost.

如果您正在写入控制台,并且需要确保每条消息在写入后立即显示。

If you're writing to the console, and need to make sure that every message is shown as soon as it's written.

这篇关于如何为PrintWriter使用flush()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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