00:00

BufferedReader Class in Java: Reading Text Line by Line

Last updated:

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

BufferedReader class hierarchyBufferedReader extends the abstract class Reader, which extends Object, and implements Readable, Closeable and AutoCloseable. It is created with new BufferedReader around another reader or with Files.newBufferedReader, and LineNumberReader extends it.ObjectextendsReaderabstract classextendsBufferedReaderbuffers text, reads whole linesReadableCloseableAutoCloseableimplementsCommon ways to createnew BufferedReader(reader)Files.newBufferedReader(path)subclass: LineNumberReader

Swipe sideways to see the whole diagram.

3. Constructors of BufferedReader

ConstructorDescription
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

MethodDescription
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.

StatusCodeReport.java
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);
    }
}
Output
Requests by status: {200=3, 404=1, 500=1}

How the code works

  1. A text block (Java 15) creates the sample log.
  2. readLine() returns one line at a time and null at the end of the file, which ends the loop.
  3. 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().

ExpenseTotal.java
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);
    }
}
Output
Total spent on food: 830

How the code works

  1. lines() returns a Stream<String> that reads lines only as they are needed.
  2. skip(1) drops the header; filter keeps food rows; mapToInt and sum() add the amounts.
  3. Closing the BufferedReader in 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 ""; only null means 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 to FileReader.
  • Reading huge files with Files.readAllLines(). BufferedReader keeps only one line in memory.

8. Java Version Improvements and Java 25 Updates

Java versionChange
Java 1.1BufferedReader with readLine().
Java 7 and 8Files.newBufferedReader(); lines() returns a stream.
Java 15Text blocks make multi-line test data easy to write.
Java 25No API changes. For keyboard input, java.lang.IO.readln() is a simpler alternative.

9. Summary

  • BufferedReader reads text efficiently and line by line.
  • readLine() returns null at the end of the input.
  • lines() turns the input into a Stream<String>.
  • Create it with Files.newBufferedReader() for files, and close it with try-with-resources.

Related Tutorials

10. Official Java Documentation References