Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 704
Ali Kashanchi Avatar asked Oct 04 '13 14:10

Ali Kashanchi


3 Answers

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.

like image 162
SegFault Avatar answered Oct 18 '22 19:10

SegFault


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.

like image 3
Rogue Avatar answered Oct 18 '22 18:10

Rogue


Here is what the say documentation.

like image 2
Anton Dozortsev Avatar answered Oct 18 '22 20:10

Anton Dozortsev