Java - IO - Buffer Streams

> Procedural Languages > Java > Java - IO (Input/Output) - (File System|File|Console)

1 - About

Without buffer, each read or write request is handled directly by the underlying OS. This can make a program much less efficient, since each such request often triggers:

  • disk access,
  • network activity,
  • or some other operation

that is relatively expensive.

Advertising

3 - Streams

Java has buffer streams:

4 - Operations

4.1 - Flush

Flushing is a specific operations of Buffered Streams.

Flushing an output stream forces any buffered output bytes to be written out.

The general contract of flush is that calling it is an indication that, if any bytes previously written have been buffered by the implementation of the output stream, such bytes should immediately be written to their intended destination.

The buffer can be flushed:

  • automatically. The output classes must support the autoflush configuration.
  • or by invoking its flush method. (The flush method is valid on any output stream, but has no effect unless the stream is buffered)

When a close method is called on a such a class, it automatically performs a flush. There is no need to explicitly call flush before calling close.