Question

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

Was it helpful?

Solution

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.

OTHER TIPS

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.

Here is what the say documentation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top