EMZETT.
Login

BufferedWriter (Buffered Output)

In short: A wrapper around an output stream that first collects data to be written in memory and writes it in larger blocks at once, instead of writing physically immediately on every single call.

In more detail: This saves expensive individual writes to disk or network and significantly speeds up especially many small, consecutive write operations. Important: a buffer isn’t automatically flushed immediately — without a final “flush” or closing of the stream, buffered but not-yet-written data can be lost.

In Depth

The speed difference between buffered and unbuffered writing is dramatic for many small operations:

// UNBUFFERED: every single write() call can trigger an expensive system call
FileWriter raw = new FileWriter("file.txt");
for (String line : tenThousandLines) {
    raw.write(line);   // potentially 10,000 individual, slow write accesses
}
 
// BUFFERED: data collects in memory, physical writing happens in a few large blocks
BufferedWriter buffered = new BufferedWriter(new FileWriter("file.txt"));
for (String line : tenThousandLines) {
    buffered.write(line);   // initially just lands in the buffer
}
buffered.close();             // this is where the remaining buffered data is actually written

The buffer is basically an intermediate store (an internal array) in working memory: instead of immediately passing every written value on to the operating system (which then itself decides when to actually write it physically to the storage device — also often buffered), the BufferedWriter first collects a larger amount and then hands it over in a single, more efficient call.

The most important consequence of this design: a write() call does NOT guarantee that the data is already physically saved — it can still exist exclusively in the buffer. If the program crashes before the buffer is flushed, this data is lost, even though the code apparently wrote successfully. There are two ways to flush the buffer:

  • flush() — explicitly flushes the buffer without closing the stream (useful when writing should continue, but the current state already has to be secured).
  • close() — flushes the buffer AND closes the stream (the usual, recommended variant at the end of use, ideally guaranteed via try-with-resources).

See also: I/O Streams, BufferedReader, Write Files