简体   繁体   English

如何为PrintWriter使用flush()

[英]How to use flush() for PrintWriter

I have some codes like this: 我有一些像这样的代码:

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

Is the flush() in each 'for' statement necessarily? 每个'for'语句中的flush()是否必然? I heard that flush() would auto invoke when invoke close() . 我听说flush()会在调用close()时自动调用。 If I write code like this: 如果我写这样的代码:

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

and I wouldn't write pw.flush() anymore? 我不会再写pw.flush()了吗? Thanks. 谢谢。

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. 它的作用是确保在调用flush()之前写入writer的任何内容都写入底层流,而不是放在某个内部缓冲区中。

The method comes in handy in several types of circumstances: 该方法在几种情况下派上用场:

  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. 如果另一个进程(或线程)需要在写入文件时检查该文件,则另一个进程看到所有最近的写入是很重要的。

  2. If the writing process might crash, and it's important that no writes to the file get lost. 如果写入过程可能会崩溃,那么重要的是不会丢失对文件的写入。

  3. If you're writing to the console, and need to make sure that every message is shown as soon as it's written. 如果您正在写入控制台,并且需要确保每条消息在写入后立即显示。

The second option is better to use, as it will create an autoflushable PrintWriter object. 第二个选项更好用,因为它将创建一个可自动清洗的PrintWriter对象。 And if you use first case, then I don't think flush() is required in your example case. 如果您使用第一种情况,那么我认为在您的示例案例中不需要flush()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM