Java - BufferedOutputStream flush() method



Description

The Java BufferedOutputStream flush() method flushes the buffered output bytes to write out to the underlying output stream. The flush() method is used to force any buffered output bytes to be written to the underlying output stream. This ensures that all data is written out immediately, rather than waiting for the buffer to fill up.

Declaration

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

public void flush()

Parameters

NA

Return Value

This method does not return any value.

Exception

IOException − If an I/O error occurs.

Assumption

Assuming we have a text file example.txt, which has the following content. This file will be used as an input for our example programs −

ABCDEFGHIJKLMNOPQRSTUVWXYZ

Example - Using flush() method

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

BufferedOutputStreamDemo.java

package com.tutorialspoint;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;

public class BufferedOutputStreamDemo {
   public static void main(String[] args) throws Exception {
      FileInputStream is = null;
      BufferedInputStream bis = null;
      ByteArrayOutputStream baos = null;
      BufferedOutputStream bos = null;
		
      try {
         // open input stream example.txt for reading purpose.
         is = new FileInputStream("example.txt");

         // input stream is converted to buffered input stream
         bis = new BufferedInputStream(is);

         // creates a new byte array output stream
         baos = new ByteArrayOutputStream();

         // creates a new buffered output stream to write 'baos'
         bos = new BufferedOutputStream(baos);
		
         int value;

         // the file is read to the end
         while ((value = bis.read()) != -1) {
            bos.write(value);
         }

         // invokes flush to force bytes to be written out to baos
         bos.flush();

         // every byte read from baos
         for (byte b: baos.toByteArray()) {
            
            // converts byte to character
            char c = (char)b;
            System.out.print(c);
         }
      } catch(IOException e) {
         // if any IOException occurs 
         e.printStackTrace();
      } finally {
         // releases any system resources associated with the stream
         if(is!=null)
            is.close();
         if(bis!=null)
            bis.close();
         if(baos!=null)
            baos.close();
         if(bos!=null)
            bos.close();
      }	
   }
}

Output

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

ABCDEFGHIJKLMNOPQRSTUVWXYZ

Example - Using flush() to Ensure Data is Written Immediately

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

BufferedOutputStreamDemo.java

package com.tutorialspoint;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class BufferedOutputStreamDemo {
   public static void main(String[] args) {
      String data = "This is an example of flush().";

      try (BufferedOutputStream bos = new BufferedOutputStream(
         new FileOutputStream("example.txt"))) {
         // Write data to the buffer
         bos.write(data.getBytes());
         System.out.println("Data written to buffer.");

         // Flush the buffer, ensuring data is written to the file
         bos.flush();
         System.out.println("Buffer flushed. Data written to the file.");
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}

Output

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

Data written to buffer.
Buffer flushed. Data written to the file.

Explanation

  • Data Source− A string "This is an example of flush()." is written to a file (example.txt) using a BufferedOutputStream.

  • Buffered Writing

    • Data is written to the buffer first.

    • The flush() method ensures that the buffered data is pushed to the underlying file immediately.

  • Output

    • Without flush(), the data might remain in the buffer and not be written to the file until the buffer is full or the stream is closed.

    • The flush() ensures the file contains the data immediately after the method call.

Example - Flushing Data Before Closing the Stream

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

BufferedOutputStreamDemo.java

package com.tutorialspoint;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class BufferedOutputStreamDemo {
   public static void main(String[] args) {
      String data = "BufferedOutputStream flush example.";

      // Use ByteArrayOutputStream for demonstration
      try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
         BufferedOutputStream bos = new BufferedOutputStream(baos)) {

         // Write data to the buffer
         bos.write(data.getBytes());
         System.out.println("Data written to buffer.");

         // Flush the buffer to the ByteArrayOutputStream
         bos.flush();
         System.out.println("Buffer flushed. Data sent to the ByteArrayOutputStream.");

         // Print the content of the ByteArrayOutputStream
         System.out.println("Data in ByteArrayOutputStream: " + baos.toString());
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}

Output

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

Data written to buffer.
Buffer flushed. Data sent to the ByteArrayOutputStream.
Data in ByteArrayOutputStream: BufferedOutputStream flush example.

Explanation

  • Data Source− A string "BufferedOutputStream flush example." is written to a BufferedOutputStream, which wraps a ByteArrayOutputStream.

  • Buffered Writing

    • The data is buffered in the BufferedOutputStream first.

    • The flush() method forces the data to be written to the ByteArrayOutputStream.

  • Verifying the Output

    • The content of the ByteArrayOutputStream is printed to verify that the data was flushed successfully.

Key Points

  • Purpose of flush()

    • Ensures that buffered data is written to the underlying stream immediately.

    • Useful for ensuring real-time updates to the output stream (e.g., writing to files or network streams).

  • Common Use Cases

    • Writing data to a file or stream that needs to be visible immediately.

    • Flushing buffered data before closing the stream to avoid data loss.

  • Limitations

    • Failing to call flush() explicitly may result in data not being written out until the buffer is full or the stream is closed.

java_io_bufferedoutputstream.htm
Advertisements