Flushing and Closing: Ensuring Data Persistence
You'll learn why properly flushing and closing character streams is critical to prevent data loss and resource leaks.
The Problem: Data in Limbo
When you write characters using FileWriter or other Writer classes, your data doesn't always go straight to disk. Writers often buffer data internally for efficiency—like collecting several characters before making the expensive trip to actually write to the file. This means your data might be sitting in memory, not yet persisted.
Think of it like a postal service: You drop letters into a mailbox (writer buffer), but they don't actually get sent until the mail carrier comes (flush or close operation). If you never signal that collection, your letters might never be delivered.
flush(): Forcing Data Out
The flush() method tells the writer to immediately push any buffered data to its destination:
writer.flush(); // Forces buffered characters to disk NOW
Use flush() when you need to ensure data is written immediately—for example, when writing log entries that you want visible right away, or before long operations where you want partial results saved.
close(): The Final Step
The close() method both flushes any remaining buffered data AND releases system resources (file handles):
writer.close(); // Flushes remaining data, releases file handle
Always close your writers. Unclosed streams can leak file handles (exhausting system resources) and lose buffered data that never gets written to disk.
The Try-With-Resources Pattern
The safest approach combines both concepts with automatic resource management:
try (FileWriter writer = new FileWriter("output.txt")) {
writer.write("Important data");
// Automatically flushed and closed at end of try block
}
Key Takeaway: Always close character streams to ensure buffered data is persisted and system resources are released—use try-with-resources to handle this automatically and safely, or call close() explicitly if needed.