2013-10-04 108 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()来写存储在输出缓冲区的任何数据。缓冲区将文本存储到某一点,然后在填满时写入。如果您在不刷新缓冲区的情况下终止程序,则可能会丢失数据。

相关问题