Java - BufferedWriter flush() method



Description

The Java BufferedWriter flush() flushes the characters from a write buffer to the character or byte stream as an intended destination.

flush() method is used to write text to a character-based output stream, buffering the characters for efficient writing. The flush() method plays a crucial role in ensuring that all the buffered data is written to the underlying output destination (e.g., a file) without closing the writer.

The flush() method clears the buffer by forcing any buffered data to be written immediately. This is especially useful when you want to ensure that data is saved or displayed without waiting for the buffer to fill up or the writer to be closed.

Declaration

Following is the declaration for java.io.BufferedWriter.flush() method.

public Writer flush()

Parameters

NA

Return Value

This method does not return any value.

Exception

IOException − If an I/O error occurs.

Key Features of the flush() Method

  • Forces Data to Be Written− It writes all the buffered characters to the output stream.

  • Does Not Close the Writer− Unlike the close() method, flush() keeps the writer open for further use.

  • Use Cases− Useful in scenarios where you want to ensure data is written without closing the writer, such as logging, writing intermediate results, or flushing data in long-running processes.

Example - Using flush() method

The following example shows the usage of Java BufferedWriter flush() method.

BufferedWriterDemo.java

package com.tutorialspoint;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.StringWriter;

public class BufferedWriterDemo {
   public static void main(String[] args) throws IOException {
      StringWriter sw = null;
      BufferedWriter bw = null;
      String letters = "ABCDEFGHIJK";
      
      try {
         // create string writer
         sw = new StringWriter();
         
         //create buffered writer
         bw = new BufferedWriter(sw);
         
         // for each character in the string
         for (char c: letters.toCharArray()) {
            
            // append character to the writer
            bw.append(c);
            
            // flush the characters to the intended stream
            bw.flush();
            
            // print string buffer from string writer
            System.out.println(sw.getBuffer());
         }
      } catch(IOException e) {
         // if I/O error occurs
         e.printStackTrace();
      } finally {
         // releases any system resources associated with the stream
         if(sw!=null)
            sw.close();
         if(bw!=null)
            bw.close();
      }
   }
}

Let us compile and run the above program, this will produce the following result −

A
AB
ABC
ABCD
ABCDE
ABCDEF
ABCDEFG
ABCDEFGH
ABCDEFGHI
ABCDEFGHIJ
ABCDEFGHIJK

Example - Using flush() to Save Data Without Closing the Writer

The following example shows the usage of Java BufferedWriter flush() method.

BufferedWriterDemo.java

package com.tutorialspoint;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class BufferedWriterDemo {
   public static void main(String[] args) {
      String filePath = "example.txt";
      String content = "Hello, World!\nThis is the flush() method in action.";

      try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
         // Write content to the buffer
         writer.write(content);

         // Flush the buffer to ensure data is written to the file
         writer.flush();
         System.out.println("Data flushed to file without closing the writer.");

         // Write more content after flushing
         writer.write("\nAdditional content after flushing.");
      } catch (IOException e) {
         System.err.println("An error occurred: " + e.getMessage());
      }
   }
}

Output

Let us compile and run the above program, this will produce the following result −

Data flushed to file without closing the writer.

File Output

Following will be the content of example.txt file

Hello, World!
This is the flush() method in action.
Additional content after flushing.

Explanation

  • A BufferedWriter is created to write data to a file (example.txt).

  • The write() method writes the content to the buffer but does not immediately write it to the file.

  • The flush() method is called to force the buffered data to be written to the file without closing the writer.

  • Additional content is written after the flush, demonstrating that the writer remains open for further use.

Example - Flushing Data Periodically in a Long-Running Process

The following example shows the usage of Java BufferedWriter flush() method.

BufferedWriterDemo.java

package com.tutorialspoint;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class BufferedWriterDemo {
   public static void main(String[] args) {
      String filePath = "example.txt";

      try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
         // Simulate writing data in a loop
         for (int i = 1; i <= 5; i++) {
            writer.write("Line " + i + ": This is a periodic flush example.\n");

            // Flush the buffer after writing each line
            writer.flush();
            System.out.println("Flushed data after writing line " + i);
         }
      } catch (IOException e) {
         System.err.println("An error occurred: " + e.getMessage());
      }
   }
}

Output

Let us compile and run the above program, this will produce the following result −

Flushed data after writing line 1
Flushed data after writing line 2
Flushed data after writing line 3
Flushed data after writing line 4
Flushed data after writing line 5

File Output

Following will be the content of example.txt file

Line 1: This is a periodic flush example.
Line 2: This is a periodic flush example.
Line 3: This is a periodic flush example.
Line 4: This is a periodic flush example.
Line 5: This is a periodic flush example.

Explanation

  • A BufferedWriter is created to write data to a file (example.txt).

  • Inside a loop, data is written line by line, simulating a scenario where data is generated or logged incrementally.

  • After writing each line, the flush() method is called to ensure that the data is immediately written to the file, even before the loop completes.

  • This approach is useful in scenarios such as logging real-time events or writing large data incrementally.

When to Use flush()

  • Intermediate Data Saving− If you want to save buffered data without closing the writer.

  • Real-Time Logging− To write logs immediately without waiting for the writer to close.

  • Long-Running Processes− Periodically flush data in scenarios like batch processing or writing large files incrementally.

Key Differences Between flush() and close()

Sr.No. Aspect flush() close()
1 Purpose Writes buffered data to the output stream. Writes buffered data and closes the writer.
2 Writer Availability The writer remains open after flushing. The writer is closed after execution.
3 Use Case For saving intermediate data without closing. For completing writing operations and cleanup.

Conclusion

The flush() method in the BufferedWriter class is a powerful tool for ensuring that buffered data is written to the underlying stream without closing the writer. Whether you're writing to a file or logging data in real-time, using flush() allows you to save data efficiently and ensure its immediate availability.

The provided examples showcase practical scenarios where flush() is particularly useful, making it an essential method for writing applications.

java_io_bufferedwriter.htm
Advertisements