What is the purpose of the flush() method of the BufferedWriter class in java?


While you are trying to write data to a Stream using the BufferedWriter object, after invoking the write() method the data will be buffered initially, nothing will be printed.

The flush() method is used to push the contents of the buffer to the underlying Stream.

Example

In the following Java program, we are trying to print a line on the console (Standard Output Stream). Here we are invoking the write() method by passing the required String.

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
public class BufferedWriterExample {
   public static void main(String args[]) throws IOException {
      //Instantiating the OutputStreamWriter class
      OutputStreamWriter out = new OutputStreamWriter(System.out);
      //Instantiating the BufferedWriter
      BufferedWriter writer = new BufferedWriter(out);
      //Writing data to the console
      writer.write("Hello welcome to Tutorialspoint");
   }
}

But, since you haven’t flushed the contents of the Buffer of the BufferedWriter nothing will be printed.

To resolve this invoke the flush() method after the executing the write().

Example

 Live Demo

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
public class BufferedWriterExample {
   public static void main(String args[]) throws IOException {
      //Instantiating the OutputStreamWriter class
      OutputStreamWriter out = new OutputStreamWriter(System.out);
      //Instantiating the BufferedWriter
      BufferedWriter writer = new BufferedWriter(out);
      //Writing data to the console
      writer.write("Hello welcome to Tutorialspoint");
      writer.flush();
   }
}

Output

Hello welcome to Tutorialspoint

Updated on: 15-Oct-2019

277 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements