Course contentsShow
← Java
Lesson 1937 of 2,87039. File I/O: Basic Byte StreamsFree lesson

flush: Forcing Buffered Data to Disk

Call flush() to write accumulated bytes immediately, ensuring data persistence before program termination.

Forcing Buffered Data to Disk with flush()

You'll learn how to ensure buffered data is immediately written to disk using the flush() method, guaranteeing persistence before your program ends.

Why Flushing Matters

When you write data to a BufferedOutputStream, it doesn't immediately go to disk—it sits in memory in an internal buffer (typically 8KB). This is great for performance, but creates a risk: if your program crashes or terminates unexpectedly before the buffer fills up, that data could be lost forever.

Think of it like a delivery truck that waits to fill up before making a trip. If the truck never gets full and the warehouse closes, some packages never get delivered.

What flush() Does

The flush() method forces the stream to write all accumulated bytes from its internal buffer to the underlying destination immediately, without waiting for the buffer to fill.

BufferedOutputStream buffOut = new BufferedOutputStream(
    new FileOutputStream("data.bin")
);

buffOut.write(someBytes);
buffOut.flush(); // Forces immediate write to disk

When to Use flush()

You should explicitly call flush():

  • Before program termination (if you might not call close())
  • At critical save points where data loss would be unacceptable
  • When coordinating with other processes that need to read your output immediately

Note: close() automatically calls flush(), so if you properly close your streams, you're already covered for normal scenarios. But flush() is your safety net for ensuring intermediate persistence without closing the stream.

Key Takeaway:
Call flush() on buffered output streams to immediately write accumulated data to disk, ensuring persistence at critical points without waiting for the buffer to fill or the stream to close.