Do I need to explicitly use flush() method there?

Viewed 94

Do I need there to explicitly writer.flush() or not? I think that after leaving save() method writer may not write data to the outputStream

import java.io.*;

public class Test
{
    public int i = 5;
    
    public void save(OutputStream outputStream) throws Exception
    {
        PrintWriter writer = new PrintWriter(outputStream);
        writer.println(i);
        writer.flush(); // necessarily or not?
    }
}
1 Answers

From flush documentation:

 /**
  * Flushes the stream.  If the stream has saved any characters from the
  * various write() methods in a buffer, write them immediately to their
  * intended destination.  Then, if that destination is another character or
  * byte stream, flush it.  Thus one flush() invocation will flush all the
  * buffers in a chain of Writers and OutputStreams.
  *
  * <p> If the intended destination of this stream is an abstraction provided
  * by the underlying operating system, for example a file, then flushing the
  * stream guarantees only that bytes previously written to the stream are
  * passed to the operating system for writing; it does not guarantee that
  * they are actually written to a physical device such as a disk drive.
  *
  * @throws java.io.IOException
  *          If an I/O error occurs
  */

Therefore if you need to guarantee the bytes are written to the next stream, call it.

Please take a look at checkError which according to its documentation:

* Flushes the stream if it's not closed and checks its error state.
Related