2017-06-07 31 views
1

从的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构造函数。

回答

0

我使用调试器一步一步走到,这是我发现: enter image description here String s显示在第527行之后的主机,所以它的前行528,其中具有\n的检查完成。

charOut.flushBuffer()内心深处,有一个叫下面的方法:enter image description here

其中,检查有关\n丢失。

流动是因为它遵循:

  1. System.out#print(String s)电话PrintStream#print(String s)
  2. PrintStream#print(String s)来电PrintStream#write(String s)
  3. PrintStream#write(String s)来电OutputSteamWriter#flushBuffer()
  4. OutputStreamWriter#flushBuffer()来电StreamEncoder#flushBuffer()
  5. StreamEncoder#flushBuffer()来电StreamEncoder#implFlushBuffer()
  6. StreamEncoder#implFlushBuffer()来电StreamEncoder#writeBytes()
  7. StreamEncoder#writeBytes()来电PrintStream#write(byte buf[], int off, int len)这冲刷了buffor if(autoFlush)

以上是最重要的片段。在此流程中似乎不会调用BufferedWriter

+0

这正是OP所问的 - 在这种情况下为什么会影响事物? –

+0

API说,如果自动刷新设置为true,那么只有println被刷新,而不是打印(!!!)。我在PrintStream(它的第一段)中引用了apidoc:“或者,可以创建PrintStream以便自动刷新;这意味着在写入字节数组后,会自动调用flush方法,调用其中一个println方法,或者一个换行符或字节('\ n')被写入。“ – LrnBoy

+0

我也猜测它的自动冲洗设置为true,但任何人都可以指向它发生的地方吗?我目前找不到这个地方... – LrnBoy