Java 为什么我们使用system.out.flush()?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19183955/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 14:52:06  来源:igfitidea点击:

why we use system.out.flush()?

javasystem.out

提问by Ali Kashanchi

Can someone please explain why we we would use system.out.flush()in a simpler way? If there could be a chance of losing data, please provide me with an example. If you comment it in the code below nothing changes!

有人可以解释为什么我们会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);

   }
   }
}

Thank you

谢谢

采纳答案by SegFault

When you write data out to a stream, some amount of buffering will occur, and you never know for sure exactly when the last of the data will actually be sent. You might perform many operations on a stream before closing it, and invoking the flush() method guarantees that the last of the data you thought you had already written actually gets out to the file.

当您将数据写入流时,会发生一定量的缓冲,并且您永远无法确切知道最后一个数据何时实际发送。您可能会在关闭流之前对它执行许多操作,并且调用 flush() 方法可确保您认为已经写入的最后一个数据实际上已到达文件中。

Extract from Sun Certified Programmer for Java 6 Exam by Sierra & Bates.

摘自Sierra & Bates 的 Sun 认证程序员 Java 6 考试

In your example, it doesn't change anything because System.outperforms auto-flushing meaning that everytime a byte in written in the buffer, it is automatically flushed.

在您的示例中,它不会更改任何内容,因为System.out执行自动刷新意味着每次写入缓冲区的字节都会自动刷新。

回答by Rogue

You use System.out.flush() to write any data stored in the out buffer. Buffers store text up to a point and then write when full. If you terminate a program without flushing a buffer, you could potentially lose data.

您使用 System.out.flush() 写入存储在输出缓冲区中的任何数据。缓冲区将文本存储到一个点,然后在满时写入。如果在不刷新缓冲区的情况下终止程序,则可能会丢失数据。

回答by Anton Dozortsev

Here is what the say documentation.

这就是说文档的内容