2016-09-10 26 views
4

我對Java很新穎。Java'System.err.format''''n'後跟'System.out.println',println打印在中間

我使用的是Ubuntu 16.04,JDK 8u101,Netbeans8.1。

當試圖驗證碼:

public static void main(String[] args) { 
    System.err.format("1st Line %nPrints At 3rd Line,Shouldn't this be In 2nd Line "); 
    System.out.println("Shouldn't this be the third line,prints at 2nd line"); 
} 

輸出是:

This Prints At 1st Line 
Shouldn't this be the third line, but prints at 2nd line 
This Prints At 3rd Line, Shouldn't this be In 2nd Line 

爲什麼 「System.out.println」 打印在中間? 不應該最後打印。

我 「%n」 試圖在最後& System.err.flush()這樣的:

System.err.format("1st Line %nPrints At 3rd Line,Shouldn't this be In 2nd Line%n"); 
System.err.flush(); 
System.out.println("Shouldn't this be the third line,prints at 2nd line"); 

還是相同的輸出。

+2

您正在打印到兩個不同的流,它們只在行的末尾刷新,但System.err在第二行末尾沒有刷新。 –

回答

5

你是不是調用println()電話和System.outSystem.err之間flush()都(獨立)緩衝PrintStream(S)。

// and you need a %n on the end to make 3 lines. 
System.err.format("1st Line %nPrints At 3rd Line,Shouldn't this be In 2nd Line%n"); 
System.err.flush(); // <-- only needed if the previous write doesn't have 
        //  an implicit flush(); newline (%n) does. 
System.out.println("Shouldn't this be the third line,prints at 2nd line"); 
+0

System.err沒有被刷新,因爲它最後沒有換行符。因此您需要手動沖洗。 +1如果你添加%n,我認爲你不需要flush() –

+1

@PeterLawrey更正。 Javadoc說*可以創建一個'PrintStream'來自動刷新;這意味着在寫入字節數組後,會自動調用'flush'方法,調用'println'方法之一或者寫入換行符或字節(''\ n'')* –

+0

我試過碼。我複製粘貼,保存,然後再次運行。我得到了相同的輸出。 – Jit

相關問題