BufferedOutputStream Class in Java: Faster Byte Writing
Writing a file one byte at a time sends one request to the operating system per byte, which is slow. BufferedOutputStream collects bytes in memory and writes them in large blocks, so the same program makes only a handful of system calls.
This tutorial explains how output buffering works, the constructors and methods, and two examples: measuring the effect of buffering and showing why flush() matters.
1. What Is BufferedOutputStream in Java?
BufferedOutputStream is a filter stream that wraps another OutputStream and adds an internal buffer. It has been part of Java since version 1.0. Once a stream is wrapped, write only through the buffered stream, so bytes stay in the right order.
2. BufferedOutputStream Class Hierarchy
Swipe sideways to see the whole diagram.
3. How Output Buffering Works
write()copies bytes into the internal buffer in memory.- When the buffer is full, its whole content is passed to the wrapped stream in one call.
flush()sends whatever is in the buffer immediately;close()flushes and then closes the wrapped stream.
An array larger than the buffer is written straight through, because buffering it would not save any calls.
4. Constructors of BufferedOutputStream
| Constructor | Description |
|---|---|
BufferedOutputStream(OutputStream out) | Wraps out with a buffer of a default size chosen by the JDK. |
BufferedOutputStream(OutputStream out, int size) | Wraps out with a buffer of size bytes; throws IllegalArgumentException if size is 0 or less. |
5. Commonly Used Methods
| Method | Description |
|---|---|
void write(int b) | Adds one byte to the buffer, writing the buffer out first if it is full. |
void write(byte[] b, int off, int len) | Adds bytes to the buffer, or writes large arrays directly. |
void flush() | Forces the buffered bytes out to the wrapped stream. |
void close() | Flushes, then closes the wrapped stream (inherited from FilterOutputStream). |
6. Example: Counting Writes to the Destination
A log exporter writes 10,000 single bytes. A small FilterOutputStream subclass counts how many times data reaches the destination, first without and then with a 4 KB buffer.
import java.io.BufferedOutputStream;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
public class WriteCallCounter {
// Counts how often data is handed to the destination
static class CountingStream extends FilterOutputStream {
int calls;
CountingStream(OutputStream out) { super(out); }
@Override public void write(int b) throws IOException { calls++; out.write(b); }
@Override public void write(byte[] b, int off, int len) throws IOException { calls++; out.write(b, off, len); }
}
public static void main(String[] args) throws IOException {
CountingStream raw = new CountingStream(OutputStream.nullOutputStream());
for (int i = 0; i < 10_000; i++) {
raw.write('x');
}
System.out.println("Unbuffered: " + raw.calls + " writes to the destination");
CountingStream counter = new CountingStream(OutputStream.nullOutputStream());
try (OutputStream out = new BufferedOutputStream(counter, 4096)) {
for (int i = 0; i < 10_000; i++) {
out.write('x');
}
} // close() flushes the last 1,808 bytes
System.out.println("Buffered: " + counter.calls + " writes to the destination");
}
}
Unbuffered: 10000 writes to the destination Buffered: 3 writes to the destination
How the code works
CountingStreamcounts each call that reaches the destination, hereOutputStream.nullOutputStream(), which simply discards the bytes.- Unbuffered, every one of the 10,000
write()calls reaches the destination. - Buffered, two full 4,096-byte blocks are written when the buffer fills, and
close()writes the remaining 1,808 bytes: three calls in total.
7. Example: What Happens Without flush()
A monitoring service writes an alert to a log file, and another program checks the file immediately. Until the buffer is flushed, the alert is not in the file.
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
public class ForgottenFlush {
public static void main(String[] args) throws IOException {
Path file = Files.createTempFile("alerts", ".log");
OutputStream out = new BufferedOutputStream(new FileOutputStream(file.toFile()));
out.write("ALERT disk 91% full\n".getBytes(StandardCharsets.UTF_8));
System.out.println("Before flush: " + Files.size(file) + " bytes on disk");
out.flush(); // push the buffer to the file
System.out.println("After flush: " + Files.size(file) + " bytes on disk");
out.close();
Files.delete(file);
}
}
Before flush: 0 bytes on disk After flush: 20 bytes on disk
How the code works
- The 20-byte alert fits easily in the buffer, so after
write()nothing has reached the file yet. flush()passes the buffered bytes to the file, and its size becomes 20 bytes.- If the program crashed before flushing or closing, the alert would be lost.
8. Common Mistakes and Best Practices
- Never flushing or closing. The last block stays in memory; use try-with-resources so
close()always runs. - Flushing after every write. This removes the benefit of buffering; flush when data must be visible, for example after a complete message.
- Writing to the wrapped stream directly. Bytes can appear out of order.
- Expecting
flush()to reach the disk. It hands bytes to the operating system; useFileChannel.force()when you need them physically stored.
9. Java Version Improvements and Java 25 Updates
| Java version | Change |
|---|---|
| Java 1.0 | BufferedOutputStream with write() and flush(). |
| Java 5 and 7 | Flushable and Closeable; then try-with-resources. |
| Java 11 | OutputStream.nullOutputStream(), useful for testing as in the example. |
| Java 25 | No API changes. The default buffer size is an implementation detail; pass a size if you need a specific one. |
10. Summary
BufferedOutputStreamcollects bytes and writes them in large blocks.- It greatly reduces the number of calls to files and sockets.
- The buffer is written when it is full, on
flush()and onclose(). - Always close it, ideally with try-with-resources, so no data is lost.
Related Tutorials
- FileOutputStream Class in Java
- BufferedInputStream Class in Java
- OutputStream Class in Java
- BufferedWriter Class in Java