The flush() Method for Output Streams
What you'll learn: How to force buffered output data to be written immediately and when flush() is necessary versus automatic.
What Is flush()?
When you write data to an OutputStream, it often doesn't go directly to its final destination immediately. Instead, it sits in a buffer (a temporary holding area in memory) to improve performance. The flush() method forces any buffered data to be written out immediately, ensuring it reaches its destination.
Think of it like filling a bucket under a dripping faucet. Instead of carrying each drop to the sink individually (inefficient), you wait until the bucket fills up. But sometimes you need that water right now, even if the bucket isn't full—that's what flush() does.
When Is flush() Necessary?
Automatic flushing occurs when:
- You call
close()on the stream (it flushes before closing) - The buffer becomes full naturally
Manual flushing with flush() is necessary when:
- You need data to be visible immediately to another program or process
- You're writing critical data that must be persisted before continuing
- You're implementing network protocols where message boundaries matter
- You're writing logs or debug output that you want to see in real-time
Example Scenario
OutputStream out = // ... some output stream
out.write(new byte[]{72, 101, 108, 108, 111}); // "Hello"
// Data might still be in buffer here!
out.flush(); // Force "Hello" to be written immediately
// Now data is guaranteed to have reached destination
Without flush(), "Hello" might sit in the buffer until more data arrives or the stream closes.
Key Takeaway: Use flush() to force buffered data to be written immediately when timing matters; otherwise, trust automatic flushing at close() or when the buffer fills naturally.