BufferedReader Class in Java: Reading Text Line by Line
Most text is processed line by line: log entries, CSV rows, configuration settings. BufferedReader is the standard Java class for this job. It reads text in large blocks for speed and offers readLine() and, since Java 8, lines().
This tutorial covers its constructors and methods, and two practical examples.
1. What Is BufferedReader in Java?
BufferedReader extends Reader and wraps another reader, such as a FileReader or InputStreamReader. It fills an internal character buffer with large reads and answers small reads from memory. It was added in Java 1.1.
2. BufferedReader Class Hierarchy
Swipe sideways to see the whole diagram.
3. Constructors of BufferedReader
| Constructor | Description |
|---|---|
BufferedReader(Reader in) | Wraps in with a buffer of the default size. |
BufferedReader(Reader in, int sz) | Wraps in with a buffer of sz characters. |
For files, Files.newBufferedReader(path) creates one with UTF-8 decoding in a single call.
4. Commonly Used Methods
| Method | Description |
|---|---|
String readLine() | The next line without its line terminator, or null at the end. |
Stream<String> lines() | The remaining lines as a lazily read stream (Java 8). |
int read() | Next character, or -1. |
boolean ready() | Whether a read will not block. |
mark(int) / reset() | Remember and return to a position. |
void close() | Closes this reader and the wrapped reader. |
A line may end with \n, \r or \r\n, so files created on Windows, Linux and macOS are all read correctly.
5. Example: Counting Status Codes in a Log
A web server log records one request per line. The program counts how many requests ended with each HTTP status code.
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
import java.util.TreeMap;
public class StatusCodeReport {
public static void main(String[] args) throws IOException {
Path log = Files.createTempFile("access", ".log");
Files.writeString(log, """
GET /home 200
GET /cart 200
POST /checkout 500
GET /offers 404
GET /home 200
"""); // text block (Java 15)
Map<String, Integer> counts = new TreeMap<>();
try (BufferedReader in = Files.newBufferedReader(log, StandardCharsets.UTF_8)) {
String line;
while ((line = in.readLine()) != null) { // null means end of file
String status = line.substring(line.lastIndexOf(' ') + 1);
counts.merge(status, 1, Integer::sum);
}
}
System.out.println("Requests by status: " + counts);
Files.delete(log);
}
}
Requests by status: {200=3, 404=1, 500=1}
How the code works
- A text block (Java 15) creates the sample log.
readLine()returns one line at a time andnullat the end of the file, which ends the loop.- The status is the last word on each line, and
Map.merge()counts it.
6. Example: Processing a CSV with lines()
A personal finance app totals food expenses from a CSV file using the stream returned by lines().
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
public class ExpenseTotal {
public static void main(String[] args) throws IOException {
Path csv = Files.createTempFile("expenses", ".csv");
Files.writeString(csv, "date,category,amount\n01-11,food,450\n02-11,travel,1200\n03-11,food,380\n05-11,books,699\n");
try (BufferedReader in = Files.newBufferedReader(csv, StandardCharsets.UTF_8)) {
int foodTotal = in.lines() // Java 8: a Stream<String> of lines
.skip(1) // skip the header
.map(line -> line.split(","))
.filter(cols -> cols[1].equals("food"))
.mapToInt(cols -> Integer.parseInt(cols[2]))
.sum();
System.out.println("Total spent on food: " + foodTotal);
}
Files.delete(csv);
}
}
Total spent on food: 830
How the code works
lines()returns aStream<String>that reads lines only as they are needed.skip(1)drops the header;filterkeeps food rows;mapToIntandsum()add the amounts.- Closing the
BufferedReaderin try-with-resources also releases the file.
7. Common Mistakes and Best Practices
- Checking for an empty string instead of
null. An empty line is""; onlynullmeans the end. - Calling
readLine()twice per loop iteration. Every call consumes a line. - Creating the reader without a charset. Use
Files.newBufferedReader(path)or pass a charset toFileReader. - Reading huge files with
Files.readAllLines().BufferedReaderkeeps only one line in memory.
8. Java Version Improvements and Java 25 Updates
| Java version | Change |
|---|---|
| Java 1.1 | BufferedReader with readLine(). |
| Java 7 and 8 | Files.newBufferedReader(); lines() returns a stream. |
| Java 15 | Text blocks make multi-line test data easy to write. |
| Java 25 | No API changes. For keyboard input, java.lang.IO.readln() is a simpler alternative. |
9. Summary
BufferedReaderreads text efficiently and line by line.readLine()returnsnullat the end of the input.lines()turns the input into aStream<String>.- Create it with
Files.newBufferedReader()for files, and close it with try-with-resources.
Related Tutorials
- BufferedWriter Class in Java
- FileReader Class in Java
- InputStreamReader Class in Java
- Scanner Class in Java