立即看到System.out.print输出到控制台。因此PrintStream在每次打印后都会刷新,不仅是println?
问题描述:
从的PrintStream documentation:立即看到System.out.print输出到控制台。因此PrintStream在每次打印后都会刷新,不仅是println?
可选地,可以创建一个PrintStream以便自动冲洗; 这意味着一个字节 阵列被写入后,的其中一个println方法调用或换行符 字符或字节(“\ n”)被写入的flush方法自动调用。
然后给出代码
System.out.print("hi"); // gives console output: hi
System.out.print(7); // gives console output: 7
// prevents flushing when stream wiil be closed at app shutdown
for (;;) {
}
为什么然后我看到输出到我的控制台?控制台(来自System.out的PrintStream实例),什么都不应写入,因为到目前为止没有任何内容会被刷新!
This没有回答这个问题。我猜,答案是在源代码(私人实用工具方法BufferedWriter.flushBuffer()),但我不明白注释代码:“刷新输出缓冲区到基础字符流,而不会冲洗流本身“:如果PrintStream(与控制台输出关联),即”流本身“不刷新,则不会刷新输出到控制台!...
PrintStream.print(String) :
private void write(String s) {
try {
synchronized (this) {
ensureOpen();
textOut.write(s);
textOut.flushBuffer();
charOut.flushBuffer();
if (autoFlush && (s.indexOf('\n') >= 0))
out.flush();
}
}
catch (InterruptedIOException x) {
Thread.currentThread().interrupt();
}
catch (IOException x) {
trouble = true;
}
}
BufferedWriter.flushBuffer()的源代码:
/**
* Flushes the output buffer to the underlying character stream, without
* flushing the stream itself. This method is non-private only so that it
* may be invoked by PrintStream.
*/
void flushBuffer() throws IOException {
synchronized (lock) {
ensureOpen();
if (nextChar == 0)
return;
out.write(cb, 0, nextChar);
nextChar = 0;
}
}
更多细节也给出here。这是非常复杂的,但似乎在某个阶段BufferedWriter被赋予给PrintStream构造函数。
答
我使用调试器一步一步走到,这是我发现:
String s
显示在第527行之后的主机,所以它的前行528,其中具有\n
的检查完成。
在charOut.flushBuffer()
内心深处,有一个叫下面的方法:
其中,检查有关\n
丢失。
流动是因为它遵循:
-
System.out#print(String s)
电话PrintStream#print(String s)
。 -
PrintStream#print(String s)
来电PrintStream#write(String s)
。 -
PrintStream#write(String s)
来电OutputSteamWriter#flushBuffer()
。 -
OutputStreamWriter#flushBuffer()
来电StreamEncoder#flushBuffer()
。 -
StreamEncoder#flushBuffer()
来电StreamEncoder#implFlushBuffer()
。 -
StreamEncoder#implFlushBuffer()
来电StreamEncoder#writeBytes()
。 -
StreamEncoder#writeBytes()
来电PrintStream#write(byte buf[], int off, int len)
这冲刷了bufforif(autoFlush)
。
以上是最重要的片段。在此流程中似乎不会调用BufferedWriter
。
这正是OP所问的 - 在这种情况下为什么会影响事物? –
API说,如果自动刷新设置为true,那么只有println被刷新,而不是打印(!!!)。我在PrintStream(它的第一段)中引用了apidoc:“或者,可以创建PrintStream以便自动刷新;这意味着在写入字节数组后,会自动调用flush方法,调用其中一个println方法,或者一个换行符或字节('\ n')被写入。“ – LrnBoy
我也猜测它的自动冲洗设置为true,但任何人都可以指向它发生的地方吗?我目前找不到这个地方... – LrnBoy