Home > Java > javaTutorial > body text

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

王林
Release: 2023-09-11 12:53:02
forward
753 people have browsed it

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");
   }
}
Copy after login

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();
   }
}
Copy after login

Output

Hello welcome to Tutorialspoint
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!