BufferedReader is a class in the java.io package used to read text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines. It is the industry standard for reading large log files, configuration settings, and user input from the console.
Every time you access the disk, it takes time. Without buffering, FileReader.read() causes a physical read from the file system for every single character. BufferedReader reads a large block of characters at once and stores them in an internal buffer.
| Feature | FileReader (Unbuffered) | BufferedReader (Buffered) |
|---|---|---|
| Disk Access | Frequent (Per character) | Infrequent (Per buffer fill) |
| Speed | Slow | Very Fast |
| Methods | read() only |
read() and readLine() |
The most popular feature of BufferedReader is the readLine() method. It reads a full line of text and returns it as a String. It automatically recognizes line endings (\n or \r\n) across different operating systems.
readLine() reaches the end of the file (EOF), it returns null. This is the signal to stop your loop.
BufferedReader follows the Decorator Pattern. It doesn't read files directly; it "wraps" around another Reader (like FileReader) to give it "superpowers."
This program demonstrates the professional way to read a file line-by-line using try-with-resources to ensure all streams are closed properly.
While the default buffer is 8192 characters (8KB), you can specify a custom size if you are working with extremely large data or limited memory environments.
BufferedReader br = new BufferedReader(new FileReader("bigfile.txt"), 16384); // 16KB buffer
Sometimes you don't have a FileReader, but you have a FileInputStream (bytes). You can use InputStreamReader as a bridge to convert bytes into characters so that BufferedReader can handle them.
BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); // Reading from console
Q: What happens if you don't wrap FileReader in a BufferedReader?
A: The program will still work, but performance will be significantly degraded, especially for large files, because of frequent disk I/O operations.
Q: Is BufferedReader thread-safe?
A: Yes, the critical methods of BufferedReader are synchronized, meaning multiple threads can technically use the same reader safely, though it is usually better for each thread to have its own reader for logical clarity.
Q: What is the purpose of the mark() and reset() methods?
A: mark() "bookmarks" a position in the stream, and reset() allows the reader to jump back to that bookmark. This is useful for parsers that need to "peek" ahead and then go back.
BufferedReader is one of the most essential classes in the Java I/O toolkit. It combines the simplicity of line-by-line reading with the raw speed of memory buffering. Whether you are building a simple command-line tool or a complex server-side data processor, BufferedReader ensures your text processing is efficient and reliable.