Java.io.OutputStream.flush() Method



Description

The java.io.OutputStream.flush() method flushes this output stream and forces any buffered output bytes to be written out. The general contract of flush is that calling it is an indication that, if any bytes previously written have been buffered by the implementation of the output stream, such bytes should immediately be written to their intended destination.

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.

The flush method of OutputStream does nothing.

Declaration

Following is the declaration for java.io.OutputStream.flush() method.

public void close()

Parameters

NA

Return Value

This method does not return a value.

Exception

IOException − If an I/O error occurs.

Example

The following example shows the usage of java.io.OutputStream.flush() method.

package com.tutorialspoint;

import java.io.*;

public class OutputStreamDemo {
   public static void main(String[] args) {
      try {
         // create a new output stream
         OutputStream os = new FileOutputStream("test.txt");

         // craete a new input stream
         InputStream is = new FileInputStream("test.txt");

         // write something
         os.write('A');

         // flush the stream but it does nothing
         os.flush();

         // write something else
         os.write('B');

         // read what we wrote
         System.out.println("" + is.available());
      } catch (Exception ex) {
         ex.printStackTrace();
      }
   }
}

Let us compile and run the above program, this will produce the following result −

2
java_io_outputstream.htm
Advertisements