2013-10-04 110 views
1

有人能解釋爲什麼我們會以更簡單的方式使用system.out.flush()?如果有可能丟失數據,請給我一個例子。如果你在下面的代碼中評論它,沒有什麼改變!爲什麼我們使用system.out.flush()?

class ReverseApp{ 
    public static void main(String[] args) throws IOException{ 
    String input, output; 
    while(true){ 

     System.out.print("Enter a string: "); 
     System.out.flush(); 
     input = getString(); // read a string from kbd 
     if(input.equals("")) // quit if [Enter] 
     break; 
     // make a Reverser 
     Reverser theReverser = new Reverser(input); 
     output = theReverser.doRev(); // use it 
     System.out.println("Reversed: " + output); 

    } 
    } 
} 

謝謝

+0

默認情況下'PrintStream'的某些方法不會'flush'。 –

+1

http://stackoverflow.com/questions/7166328/when-why-to-call-system-out-flush-in-java – DT7

回答

7

當您將數據寫入流中時,會發生一定程度的緩衝,並且您無法確切知道最後一次數據的實際發送時間。在關閉流之前,您可能會在流上執行許多 操作,並調用flush()方法可確保您認爲已經寫入的最後一個數據實際上已到達該文件。

摘自Sun Certified Programmer for Java 6 Exam by Sierra & Bates

在你的例子中,它不會改變任何東西,因爲System.out執行自動刷新,這意味着每當一個字節寫入緩衝區時,它會自動刷新。

+2

不適用於所有平臺。在大多數情況下,它是在一個(依賴於平臺的)換行符上刷新的。 –

2

您使用System.out.flush()來寫存儲在輸出緩衝區的任何數據。緩衝區將文本存儲到某一點,然後在填滿時寫入。如果您在不刷新緩衝區的情況下終止程序,則可能會丟失數據。

相關問題