从 PrintStream文档:
可选地,可以创建一个 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 实例),因为到目前为止不应刷新任何内容!
这没有回答这个问题。
我想,答案在源代码中(私有实用程序方法 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;
}
}
此处还提供了更多详细信息。它非常复杂,但似乎在某个阶段 BufferedWriter 被赋予了 PrintStream 构造函数。