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

3

5

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

Cubbyhole answered 4/10, 2013 at 14:36 Comment(2)
Some methods of PrintStream do not flush by default.Jones
#7166828Antoninaantonino
T
10

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.

Thaumatrope answered 4/10, 2013 at 14:40 Comment(1)
Not on all platforms. On most it's flushed on a (platform-dependent) newline.Stigma
M
3

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.

Malissa answered 4/10, 2013 at 14:38 Comment(0)
I
2

Here is what the say documentation.

Ileac answered 4/10, 2013 at 15:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.