Creating BufferedWriter: Wrapping a Writer
What you'll learn: How to construct a BufferedWriter by wrapping a Writer (like FileWriter) to enable efficient, buffered character output.
Why Wrap a Writer?
Just as BufferedReader wraps a Reader for efficient reading, BufferedWriter wraps a Writer to batch character writes. Without buffering, every write() call would trigger a system call to write directly to disk—slow and inefficient. BufferedWriter collects characters in an internal buffer (default 8KB) and writes them in larger chunks, dramatically improving performance.
The Wrapping Pattern
The constructor signature is straightforward:
BufferedWriter(Writer out)
You pass any Writer instance—most commonly a FileWriter—to the constructor. The BufferedWriter then intercepts your write calls, stores characters in its buffer, and flushes them to the underlying writer when the buffer fills or you explicitly flush.
Typical Construction
FileWriter fileWriter = new FileWriter("output.txt");
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
This creates a chain: your code → BufferedWriter → FileWriter → disk. The buffering layer sits in the middle, batching writes for efficiency.
Custom Buffer Size
Like BufferedReader, you can specify a custom buffer size:
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter, 16384); // 16KB buffer
Larger buffers reduce the frequency of disk writes but consume more memory.
Resource Management
Always close BufferedWriter (preferably with try-with-resources). Closing automatically flushes any remaining buffered data and closes the underlying writer:
try (BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"))) {
// Use writer
} // Automatically flushes and closes
Key Takeaway: Construct a BufferedWriter by wrapping any Writer instance to batch character output into an efficient internal buffer, reducing expensive disk I/O operations.