Java.io.Writer.flush() Method



Description

The java.io.Writer.flush() method 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.

Declaration

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

public abstract void flush()

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.Writer.flush() method.

package com.tutorialspoint;

import java.io.*;

public class WriterDemo {
   public static void main(String[] args) {
      String s = "Hello World";

      // create a new writer
      Writer writer = new PrintWriter(System.out);

      try {
         // append a string
         writer.append(s);

         // flush the writer
         writer.flush();

         // append a new string in a new line
         writer.append("\nThis is an example");

         // flush the stream again
         writer.close();

      } catch (IOException ex) {
         ex.printStackTrace();
      }
   }
}

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

Hello World
This is an example
java_io_writer.htm
Advertisements