BufferedOutputStream: Batch Writing to Disk
What you'll learn: How to wrap a FileOutputStream with BufferedOutputStream to accumulate bytes in memory before writing them to disk in batches, dramatically improving write performance.
The Core Problem
When you use FileOutputStream alone, every call to write() triggers an actual disk operation. Writing one byte at a time means thousands of slow system calls. Each disk write involves mechanical delays (on HDDs) or device overhead (on SSDs).
The BufferedOutputStream Solution
BufferedOutputStream wraps an existing OutputStream (like FileOutputStream) and maintains an internal byte array buffer. Instead of writing immediately to disk, it collects bytes in memory. When the buffer fills up—or when you explicitly call flush()—it writes the entire batch to the underlying stream in one operation.
Think of it like filling a bucket: Instead of making 100 trips to pour one cup of water at a time, you fill a bucket (buffer) and make one trip carrying 100 cups at once.
Creating a BufferedOutputStream
FileOutputStream fos = new FileOutputStream("output.dat");
BufferedOutputStream bos = new BufferedOutputStream(fos);
// Write many bytes efficiently
for (int i = 0; i < 10000; i++) {
bos.write(i % 256);
}
bos.flush(); // Force any remaining buffered bytes to disk
bos.close(); // Automatically flushes and closes underlying stream
The default buffer size is 8192 bytes, but you can specify a custom size:
BufferedOutputStream bos = new BufferedOutputStream(fos, 16384);
When to Flush
Always call flush() before closing if timing matters, or when you need data written immediately. Closing automatically flushes, but explicit flushing gives you control over when data hits disk.
Key Takeaway: Wrap FileOutputStream with BufferedOutputStream to batch writes into memory, reducing expensive disk operations from thousands to dozens—often improving performance by 10–100x for small writes.