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

Flushing Output Streams

Learn when and why to call flush() to ensure buffered data is written to the underlying destination.

Flushing Output Streams

What you'll learn: When and why to call flush() to ensure buffered data is actually written to its destination.


The Problem with Internal Buffers

When you write data to an output stream, it doesn't always go directly to the file or destination immediately. Most streams use an internal buffer—a temporary holding area in memory—to collect small writes and batch them together. This improves performance by reducing the number of expensive disk or network operations.

Think of it like loading a delivery truck: instead of making a trip for every single package, you fill the truck and make one efficient journey. But what if you need a package delivered right now, before the truck is full?


What flush() Does

The flush() method forces any buffered data to be written immediately to the underlying destination (disk, network, etc.). After calling flush(), you're guaranteed that everything you've written so far has left the buffer and reached its target.

FileOutputStream fos = new FileOutputStream("data.bin");

fos.write(65);  // Might sit in buffer
fos.write(66);  // Might sit in buffer
fos.flush();    // NOW both bytes are written to disk

fos.write(67);
fos.close();    // Automatically flushes before closing

When to Call flush()

  • Real-time requirements: When another process needs to read the data immediately
  • Long-running streams: Periodically flush to prevent data loss if the program crashes
  • Network streams: Ensure messages are sent promptly
  • Before reading responses: Flush output before waiting for input

Note: close() automatically calls flush(), so you don't need to flush right before closing.


Key Takeaway: Call flush() on output streams when you need to guarantee that buffered data is immediately written to its destination, rather than waiting for the buffer to fill or the stream to close.