Java IO Tutorial - Java OutputStream.flush()








Syntax

OutputStream.flush() has the following syntax.

public void flush()  throws IOException

Example

In the following code shows how to use OutputStream.flush() method.

//ww w .j  a  v a  2s.c om
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

public class Main {

  public static void main(String[] args) {
    try {

      OutputStream os = new FileOutputStream("test.txt");

      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());
      os.close();
      is.close();
    } catch (Exception ex) {
      ex.printStackTrace();
    }

  }
}

The code above generates the following result.