← Back to Chapters

BufferedReader & BufferedWriter

? BufferedReader & BufferedWriter

? Quick Overview

java.io BufferedReader and BufferedWriter are character-based I/O classes in Java that improve performance by using an internal buffer when reading or writing text data.

? Key Concepts

  • Used for efficient reading and writing of characters
  • Works on top of FileReader and FileWriter
  • Reduces direct disk access using buffering
  • Commonly used for text files

? Syntax / Theory

BufferedReader reads text line-by-line, while BufferedWriter writes text efficiently using a buffer.

? View Code Example
// Creating BufferedReader and BufferedWriter objects
BufferedReader br = new BufferedReader(new FileReader("input.txt"));
BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"));

? Code Example

? View Code Example
// Reading from a file and writing to another file using buffering
import java.io.*;

class BufferedExample {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new FileReader("input.txt"));
BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"));

String line;
while ((line = br.readLine()) != null) {
bw.write(line);
bw.newLine();
}

br.close();
bw.close();
}
}

? Live Output / Explanation

Each line from input.txt is read using readLine() and written to output.txt efficiently using a buffer.

? Interactive Simulator: How Buffering Works

A BufferedWriter doesn't write to disk immediately. It waits until the buffer is full (or you manually flush it).
Buffer Size limit for this demo: 8 characters.

Internal Buffer (RAM)
 
⬇️
 

Waiting for input...

? Tips & Best Practices

  • Always close streams to avoid memory leaks
  • Use try-with-resources when possible
  • Prefer buffering for large text files

? Try It Yourself

  • Modify the program to count total lines
  • Convert all text to uppercase before writing
  • Read input from the console using BufferedReader