close vs flush: Automatic Flushing on Close
What you'll learn: You'll understand that closing a BufferedOutputStream automatically flushes buffered data, but explicitly calling flush() is safer for critical operations.
The Automatic Flush Behavior
When you call close() on a BufferedOutputStream, Java automatically invokes flush() internally before releasing the stream's resources. This ensures any buffered data sitting in memory gets written to disk before the stream shuts down.
Think of it like leaving a restaurant: when you're ready to go (close), the waiter automatically brings your check and processes your payment (flush) before you walk out the door.
Why Close Includes Flush
Since buffered streams hold data temporarily in memory, closing without flushing would risk data loss—bytes sitting in the buffer would simply vanish. Java's designers made close() automatically flush to prevent this common mistake.
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("data.bin"));
bos.write(someData);
bos.close(); // Automatically flushes before closing
When Explicit Flush Is Still Critical
Despite automatic flushing on close, explicitly calling flush() is safer in these scenarios:
- Critical data checkpoints: After writing important data that must reach disk immediately (before continuing program logic)
- Long-running streams: When the stream stays open but you need guarantees about what's been written
- Error handling: If an exception occurs before
close(), you risk losing buffered data
bos.write(criticalTransactionData);
bos.flush(); // Guarantee data reaches disk NOW
// Continue with other operations...
Key Takeaway: While close() automatically flushes a BufferedOutputStream, always call flush() explicitly when data integrity matters at specific points in your program—don't rely solely on close for critical writes.