Home >Java >javaTutorial >What is the purpose of flush() method in BufferedWriter class?

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

王林
王林forward
2023-09-11 12:53:02789browse

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

When you try to write data to a stream using a BufferedWriter object, after calling the write() method, the data will be buffered first and nothing will be printed. content.

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

Example

In the following Java program, we try to print a line on the console (standard output stream). Here we call 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");
   }
}

However, since you haven't flushed the contents of the BufferedWriter buffer, nothing will be printed.

To resolve this issue, call the flush() method write() after execution.

Example

Real-time demonstration

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

The above is the detailed content of What is the purpose of flush() method in BufferedWriter class?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete