Forcing Buffer Contents to Disk with flush()
You'll learn when and why to explicitly flush buffered writers to ensure your data reaches the disk immediately.
The Core Problem
When you write to a BufferedWriter, your characters don't immediately go to the file—they sit in an internal buffer. This improves performance, but creates a timing problem: what if you need the data written right now instead of waiting for the buffer to fill up?
Think of it like filling a bucket with water drips. Normally, you wait until the bucket is full before emptying it. But sometimes you need to empty it immediately, even if it's only half full—maybe you need to guarantee that water reaches its destination now.
When to Call flush()
You should explicitly call flush() on a BufferedWriter when:
- You need immediate visibility: Other processes or users must see the data now
- Before critical operations: Before starting a long computation where a crash would lose buffered data
- Coordinating with other I/O: When writing to logs or synchronizing with external systems
- Interactive output: When writing prompts that users need to see before responding
How flush() Works
BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"));
writer.write("Important message");
writer.flush(); // Forces buffer to disk NOW
// Continue with other operations...
Key Takeaway: Call flush() on BufferedWriter when you need to guarantee buffered data is written to the underlying stream immediately, rather than waiting for the buffer to fill or the stream to close—balancing performance with data reliability.