What is the use of in flush() and close() methods of BufferedWriter class in Java?

Java 8Object Oriented ProgrammingProgramming

The BufferedWriter class of Java is used to write stream of characters to the specified destination (character-output stream). It initially stores all the characters in a buffer and pushes the contents of the buffer to the destination, making the writing of characters, arrays and Strings efficient.

You can specify the required size of the buffer at the time of instantiating this class.

The flush() method

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().

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
raja
Published on 01-Aug-2019 16:47:24
Advertisements