Java BufferedOutputStream Class
BufferedOutputStream class in Java is a part of the java.io package. It improves the efficiency of writing data to an output stream by buffering the data. This reduces the number of direct writes to the underlying output stream, making the process faster and more efficient.
Example 1: The below Java program demonstrates how to use the bufferedOutputStream class to efficiently write data to a file by buffering the output.
// Writing data to a file
// using BufferedOutputStream
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class Geeks {
public static void main(String[] args)
{
String s
= "This is an example of BufferedOutputStream.";
try (FileOutputStream fileOutputStream
= new FileOutputStream("output.txt");
BufferedOutputStream bufferedOutputStream
= new BufferedOutputStream(fileOutputStream)) {
// Convert string to bytes and write to the
// buffered output stream
bufferedOutputStream.write(s.getBytes());
System.out.println(
"Data written to the file successfully.");
}
catch (IOException e) {
e.printStackTrace();
}
}
}
Output
Data written to the file successfully.
Declaration of BufferedOutputStream Class
public class BufferedOutputStream extends FilterOutputStream
Constructor of BufferedOutputStream class
- BufferedOutputStream(OutputStream out): Creates a buffered output stream with a default buffer size of 8192 bytes.
- BufferedOutputStream(OutputStream out, int size): Creates a buffered output stream with the specified buffer size.
Methods of BufferedOutputStream Class
Method | Action performed |
---|---|
write(int b) | Writes the specified byte to this buffered output stream |
write(byte[] b, int off, int len) | Writes len bytes from the specified byte array starting at offset off to this buffered output stream. |
flush() | Forces any buffered output bytes to be written out |
Example 2: The below Java program demonstrates how to use BufferedOutputStream class to write data to a file effectively by buffering output using methods like write(), flush() and close()
// Java program demonstrating BufferedOutputStream
import java.io.*;
class Geeks {
public static void main(String args[]) throws Exception
{
FileOutputStream fout
= new FileOutputStream("f1.txt");
// creating bufferdOutputStream obj
BufferedOutputStream bout
= new BufferedOutputStream(fout);
// illustrating write() method
for (int i = 65; i < 75; i++) {
bout.write(i);
}
byte b[] = { 75, 76, 77, 78, 79, 80 };
bout.write(b);
// illustrating flush() method
bout.flush();
// illustrating close() method
bout.close();
fout.close();
}
}
Output:

Note: A file named f1.txt
is created in the current working directory and the file will contain ABCDEFGHIJKLMNOP.