Hurry! Try our new Interactive Courses for FREE. 🥳   🚀

Java BufferedOutputStream Class

In this tutorial, we will learn about BufferedOutputStream class in Java. This class creates a buffer for the output stream and this way it is more efficient than writing directly writing into the file. It makes processing faster than the normal method.

Syntax

OutputStream os= new BufferedOutputStream(new FileOutputStream("E:\\studytonight\\myfile.txt"));  

Java BufferedOutputStream Class Constructors

Constructor Description
BufferedOutputStream(OutputStream os) This method creates the new buffered output stream which is used for writing the data to the specified output stream.
BufferedOutputStream(OutputStream os, int size) This method creates the new buffered output stream which is used for writing the data to the specified output stream with a specified buffer size.

Methods

Method Description
void write(int b) This method writes the specified byte to the buffered output stream.
void write(byte[] b, int off, int len) This method writes the bytes from the specified byte-input stream into a specified byte array, starting with the given offset
void flush() This method flushes the buffered output stream.

Example of writing data to file with BufferedOutputStream

In the example given below, we will write the string "Hello Studytonight" to the file using FileOutputStream and BufferedOutputStream.Same as we do for simple FileOutputStream here also we are using write() method to write that particular data in the file.

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class StudyTonight 
{
	public static void main(String[] args) throws IOException 
	{  
		FileOutputStream fout=new FileOutputStream("E:\\studytonight\\myfile.txt");    
		BufferedOutputStream bout=new BufferedOutputStream(fout);    
		String s="Hello Studytonight";    
		byte b[]=s.getBytes();    
		bout.write(b);    
		bout.flush();    
		bout.close();    
		fout.close();    
		System.out.println("Data written to the file successfully.");   
	}  
}


Data written to the file successfully.

Conclusion:

In this tutorial, we learned about BufferedOutputStream class. BufferedOutputStream creates a buffer so this is very fast and efficient as compared to the normal FileOutputStream class.