Combining Bridge Classes with Buffering
You'll learn how to layer BufferedReader over InputStreamReader and BufferedWriter over OutputStreamWriter for efficient, character-based I/O with encoding control.
The Power of Layered Streams
Bridge classes (InputStreamReader and OutputStreamWriter) solve the encoding problem by converting between bytes and characters. But they don't buffer data—every read or write operation hits the underlying byte stream directly. This creates the same performance bottleneck you'd face with unbuffered byte I/O.
The solution? Wrap your bridge classes in buffered character streams. This gives you both encoding control and efficient I/O.
Wrapping for Input
When reading text from a byte source (like a file or network socket), chain the streams:
InputStream fis = new FileInputStream("data.txt");
InputStreamReader isr = new InputStreamReader(fis, StandardCharsets.UTF_8);
BufferedReader br = new BufferedReader(isr);
String line = br.readLine();
br.close(); // Closes the entire chain
The BufferedReader wraps the InputStreamReader, which wraps the FileInputStream. You get UTF-8 decoding and efficient buffering.
Wrapping for Output
For writing text, the pattern mirrors input:
OutputStream fos = new FileOutputStream("output.txt");
OutputStreamWriter osw = new OutputStreamWriter(fos, StandardCharsets.UTF_8);
BufferedWriter bw = new BufferedWriter(osw);
bw.write("Hello, World!");
bw.newLine();
bw.close(); // Flushes and closes everything
The BufferedWriter accumulates characters in memory, then hands batches to OutputStreamWriter for encoding, which finally writes bytes to the file.
Why This Matters
Without buffering, each character read or write triggers encoding/decoding plus a system call. Combining bridge classes with buffering reduces system calls dramatically while maintaining full encoding flexibility—the best of both worlds.
Key Takeaway: Always wrap InputStreamReader in BufferedReader and OutputStreamWriter in BufferedWriter for production-quality character I/O that's both efficient and encoding-aware.