why we use system.out.flush()? [duplicate]

北战南征 提交于 2019-12-11 08:53:27

问题


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!

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


回答1:


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.

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

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




回答2:


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.




回答3:


Here is what the say documentation.



来源:https://stackoverflow.com/questions/19183955/why-we-use-system-out-flush

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!