什么时候/为什么要用Java调用System.out.flush() [英] When/why to call System.out.flush() in Java
问题描述
为什么标准流不需要刷新某些流(FileOutputStream
和来自套接字的流)?
Why do certain streams need to be flushed (FileOutputStream
and streams from Sockets) while the standard output stream does not?
每次有人使用System.out
PrintStream
对象时,无论是在调用println()
还是write()
时,他们都不会刷新流.但是,其他程序员习惯于将其他流称为flush()
a PrintStream
/PrintWriter
.
Every time someone uses the System.out
PrintStream
object, be it while calling println()
or write()
, they never flush the stream. However, other programmers habitually call flush()
a PrintStream
/PrintWriter
with other streams.
我最近已经向几个程序员提出了这个问题,有些人认为Java中有一些后台处理程序可以自动刷新System.out
流,但是我找不到关于它的任何文档.
I've recently asked this question to several programmers and some believe that there is some background handling in Java to auto-flush the System.out
stream but I can't find any documentation on that.
这样的事情让我想知道,简单地调用System.out.println()
是否与平台无关,因为某些系统可能需要您刷新流.
Something like this makes me wonder if simply calling System.out.println()
is platform independent as some systems may need you to flush the stream.
推荐答案
System.out
基于PrintStream
,默认情况下,每当写换行符时都会刷新.
System.out
is based around a PrintStream
which by default flushes whenever a newline is written.
来自 javadoc :
autoFlush-一个布尔值;如果为true,则每当写入字节数组,调用
println
方法之一或写入换行符或字节('\n'
)时,都会刷新输出缓冲区.
autoFlush - A boolean; if true, the output buffer will be flushed whenever a byte array is written, one of the
println
methods is invoked, or a newline character or byte ('\n'
) is written
因此,您提到的println
情况得到了明确处理,带有byte[]
的write
情况也保证可以刷新,因为它属于每当写入字节数组时".
So the println
case you mention is explicitly handled, and the write
case with a byte[]
is also guaranteed to flush because it falls under "whenever a byte array is written".
If you replace System.out
using System.setOut
and don't use an autoflushing stream, then you will have to flush it like any other stream.
库代码可能不应该直接使用System.out
,但是如果这样做,则应该谨慎刷新,因为库用户可能会覆盖System.out
来使用非刷新流.
Library code probably shouldn't be using System.out
directly, but if it does, then it should be careful to flush because a library user might override System.out
to use a non flushing stream.
任何将二进制输出写入System.out
的Java程序都应在exit
之前注意flush
,因为二进制输出通常不包含尾随换行符.
Any Java program that writes binary output to System.out
should be careful to flush
before exit
because binary output often does not include a trailing newline.
这篇关于什么时候/为什么要用Java调用System.out.flush()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!