The Wayback Machine - https://web.archive.org/web/20250123115921/https://www.geeksforgeeks.org/bufferedwriter-flush-method-in-java-with-examples/
Open In App

BufferedWriter flush() method in Java with Examples

Last Updated : 28 May, 2020
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The flush() method of BufferedWriter class in Java is used to flush the characters from the buffered writer stream.

Syntax:

public void flush()
            throws IOException

Specified By: This method is specified by the flush() method of Flushable interface.

Overrides: This method overrides the flush() method of Writer class.

Parameters: This method does not accept any parameter.

Return value: This method does not return any value.

Exceptions: This method throws IOException if an I/O error occurs.

Below programs illustrate flush() method in BufferedWriter class in IO package:

Program 1:




// Java program to illustrate
// BufferedWriter flush() method
  
import java.io.*;
  
public class GFG {
    public static void main(String[] args)
        throws IOException
    {
  
        // Create the string Writer
        StringWriter stringWriter
            = new StringWriter();
  
        // Convert stringWriter to
        // bufferedWriter
        BufferedWriter buffWriter
            = new BufferedWriter(
                stringWriter);
  
        // Write "GEEKS" to buffer writer
        buffWriter.write(
            "GEEKSFORGEEKS", 0, 5);
  
        // Flush the buffer writer
        buffWriter.flush();
  
        System.out.println(
            stringWriter.getBuffer());
    }
}


Output:

GEEKS

Program 2:




// Java program to illustrate
// BufferedWriter flush() method
  
import java.io.*;
  
public class GFG {
    public static void main(String[] args)
        throws IOException
    {
        // Create the string Writer
        StringWriter stringWriter
            = new StringWriter();
  
        // Convert stringWriter to
        // bufferedWriter
        BufferedWriter buffWriter
            = new BufferedWriter(
                stringWriter);
  
        // Write "GEEKS" to buffered writer
        buffWriter.write(
            "GEEKSFORGEEKS", 0, 5);
  
        // Flush the buffered writer
        buffWriter.flush();
  
        System.out.println(
            stringWriter.getBuffer());
  
        // Write "GEEKSFORGEEKS"
        // to buffered writer
        buffWriter.write(
            "GEEKSFORGEEKS", 5, 8);
  
        // Flush the buffered writer
        buffWriter.flush();
  
        System.out.println(
            stringWriter.getBuffer());
    }
}


Output:

GEEKS
GEEKSFORGEEKS

References:
https://docs.oracle.com/javase/10/docs/api/java/io/BufferedWriter.html#flush()



Next Article
Practice Tags :

Similar Reads

three90RightbarBannerImg