Description

On this document we will be showing a java example on how to use the flush() method of BufferedOutputStream Class. This method flushes this buffered output stream. This forces any buffered output bytes to be written out to the underlying output stream.

Specified by:

  • flush in interface Flushable

Override by:

  • flush in class FilterOutputStream

Throws:

  • IOException – If an I/O error occurs

Method Syntax

public void flush()
throws IOException

Method Argument

Data Type Parameter Description
N/A N/A N/A

Method Returns

This method returns void.

Compatibility

Requires Java 1.0 and up

Java BufferedOutputStream flush() Example

Below is a java code demonstrates the use of flush() method of BufferedOutputStream class. The example presented might be simple however it shows the behaviour of the flush().

package com.javatutorialhq.java.examples;

import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Scanner;



/*
 * This example source code demonstrates the use of  
 * flush() method of BufferedOutputStream class
 */

public class BufferedOutputStreamFlushExample {

	public static void main(String[] args) {	
		
		
		try {
			// initialize File object
			File f = new File("C:javatutorialhqoutputtest_out.txt");
			
			// instantiate a new FileOutputStream
			FileOutputStream fos = new FileOutputStream(f);
			
			// using the above FileOutputStream
			// instantiate a BufferedOutputStream object
			BufferedOutputStream buffOut = new BufferedOutputStream(fos);
			
			BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(buffOut));
			bw.write("This is a test string");
			// flush and close the BufferedWriter
			bw.flush();
			bw.close();
			
			// flush and close the BufferedOutputStream
			buffOut.flush();
			buffOut.close();
			
			// flush and close the FileOutputStream
			fos.flush();
			fos.close();
			
			// read the contents of the file
			Scanner s = new Scanner(f);
			while(s.hasNextLine()){
				System.out.println(s.nextLine());
			}
			s.close();
		} catch (FileNotFoundException e) {
			System.out.println("File path not found");
		} catch (IOException e) {
			System.out.println("IOException occured");
		}
		

	}

}

Sample Output

Below is the sample output when you run the above example.

java BufferedOutputStream flush() example output