Flushing and Closing: flush() and close() Methods
You'll learn why explicitly flushing and closing streams is critical for data integrity and resource management.
Why flush() Matters
When you write data to an output stream, Java often buffers it in memory rather than immediately writing to disk. This improves performance, but creates a risk: if your program crashes before the buffer empties, your data is lost.
The flush() method forces any buffered data to be written immediately to the underlying destination (like a file). Think of it like hitting "save" on a document—you're making sure your changes are actually written, not just stored in temporary memory.
FileOutputStream fos = new FileOutputStream("data.txt");
fos.write(someData);
fos.flush(); // Force data to disk immediately
Why close() Is Essential
The close() method does two critical things:
-
Releases system resources: Files have limited "handles" (connections) that the operating system manages. If you never close streams, you'll eventually run out, and your program won't be able to open new files.
-
Flushes remaining data:
close()automatically callsflush()before releasing resources, ensuring no buffered data is lost.
FileOutputStream fos = new FileOutputStream("output.txt");
fos.write(data);
fos.close(); // Flushes data AND releases file handle
Analogy: Opening a stream is like checking out a library book. If you never return it (close()), the library runs out of copies for others. The book also contains your notes that won't be saved until you return it.
Key Takeaway: Always call close() on streams when finished to prevent resource leaks and data loss. Since close() flushes automatically, explicit flush() is only needed for checkpoints where the stream stays open.