BufferedReader: The Super-Fast Reader

BufferedReader: The Super-Fast Reader in Java: On an assembly line, every part an operator fits comes from central stores at the far end of the building.

The Analogy: The Line-Side Bin And The Forklift Run

On an assembly line, every part an operator fits comes from central stores at the far end of the building. Imagine if, for each single screw, the operator walked the length of the factory to stores, collected one screw, and walked back. The work would grind to a halt -- not because fetching a screw is hard, but because the walk is long and you pay for it on every single part. So real factories do not do this. A forklift makes one trip to stores, brings back a full pallet, and drops it into a line-side bin next to the operator. The operator now takes screws from the bin -- an arm's reach away -- until it runs low, at which point the forklift makes another trip. A BufferedReader is that line-side bin. Instead of asking the disk for one character at a time, it fetches a large block in a single trip, holds it in an in-memory buffer, and serves your read() and readLine() calls from there until the buffer empties and it fetches the next block.

The saving is not about the size of the load; it is about the number of trips. A forklift run costs roughly the same whether it carries one box or a full pallet, because the cost is the travel, not the cargo. A read from a disk or network is the same: the fixed overhead of the system call dwarfs the cost of the bytes moved, so making one call for 8000 characters is dramatically cheaper than 8000 calls for one character each. Buffering amortises that fixed per-trip cost across a whole block. This is why BufferedReader is fast -- not because it reads differently, but because it reads in bulk and hands you the results from close by.

This also explains the shape of the API, which confuses beginners: BufferedReader does not open files. You construct it by wrapping another reader -- new BufferedReader(new FileReader("data.txt")). The FileReader is the forklift that knows how to reach stores (the file); the BufferedReader is the bin that batches its trips. The bin cannot walk to stores itself, which is exactly why you cannot pass a filename straight to BufferedReader. It wraps a reader; it is not itself a source. See [[read-files]] for the wider picture of reading, and [[try-with-resources]] for closing the wrapper.

The failure mode is skipping the bin. A program that reads character by character straight from an unbuffered FileReader -- or worse, opens a fresh reader for every line -- is the operator walking to stores for every screw. It works on a tiny file and collapses on a large one, because it pays the per-trip cost thousands or millions of times over. The other, subtler failure is forgetting that the bin holds a live handle: an unclosed BufferedReader leaks the file descriptor of the reader it wraps, so the fix is always to declare it in a [[try-with-resources]] clause.


Syntax or Core Structure

BufferedReader wraps another Reader. In production that inner reader is a FileReader; here it is a StringReader so the run is reproducible, but the wrapping and the readLine() loop are identical.

import java.io.BufferedReader;
import java.io.StringReader;
import java.io.IOException;

public class BufferBasics {
    public static void main(String[] args) throws IOException {
        String source = "alpha
beta
gamma";

        int lines = 0;
        // Real source: new BufferedReader(new FileReader("data.txt"))
        try (BufferedReader br =
                 new BufferedReader(new StringReader(source))) {
            String line;
            while ((line = br.readLine()) != null) {
                lines++;
                System.out.println("read:     " + line);
            }
        }
        System.out.println("lines:    " + lines);
    }
}

Output:

read:     alpha
read:     beta
read:     gamma
lines:    3

The BufferedReader wraps the StringReader and serves readLine() from its buffer. The loop ends when readLine() returns null. Swapping the StringReader for a FileReader changes only the source; the buffering and the loop are unchanged.


Technical Depth: Why Wrapping, Why It Is Fast, And Look-Ahead With mark/reset

BufferedReader Wraps A Reader -- It Is A Decorator

BufferedReader adds buffering to an existing reader rather than being a source itself. This is the decorator pattern: it has the same Reader interface as the thing it wraps, so it can wrap anything that is a Reader.

Inner readerWhat it reads fromWrapped as
FileReaderA file on disknew BufferedReader(new FileReader(path))
InputStreamReaderA byte stream (e.g. network, System.in)new BufferedReader(new InputStreamReader(in))
StringReaderAn in-memory Stringnew BufferedReader(new StringReader(text))

Because the wrapper exposes the same Reader interface, the buffering is transparent: your code calls readLine() the same way regardless of what is underneath. This is also why a filename alone is not accepted -- BufferedReader needs a Reader to decorate, not a path to open.

Why Buffering Is Fast: Counting The Trips

The speed win is fewer trips to the slow source. This model counts "fetches" (system calls) for reading the same data one character at a time versus in blocks. The real BufferedReader default buffer is 8192 characters; this uses a small block to keep the numbers readable.

public class Trips {

    // Models a slow source that counts each fetch (a "trip to stores").
    static class Store {
        int trips = 0;
        final int size;
        Store(int size) { this.size = size; }

        // Unbuffered: one trip per character.
        int readEachChar() {
            for (int i = 0; i < size; i++) trips++;
            return trips;
        }
        // Buffered: one trip per block of 8.
        int readInBlocks(int block) {
            for (int i = 0; i < size; i += block) trips++;
            return trips;
        }
    }

    public static void main(String[] args) {
        int chars = 16;
        int unbuffered = new Store(chars).readEachChar();
        int buffered   = new Store(chars).readInBlocks(8);

        System.out.println("chars:       " + chars);
        System.out.println("unbuffered:  " + unbuffered);
        System.out.println("buffered:    " + buffered);
    }
}

Output:

chars:       16
unbuffered:  16
buffered:    2

Reading 16 characters one at a time costs 16 trips; reading them in blocks of 8 costs 2. The bytes moved are identical -- only the trip count changes, and the trip is what is expensive. On a real 8192-character buffer over a large file the ratio is far more dramatic, which is the whole reason to buffer.

Look-Ahead With mark And reset

BufferedReader can peek ahead and rewind, because the data is already in its buffer. mark(limit) remembers the current position; reset() returns to it. This lets you inspect a line and then un-read it.

Alongside readLine(), these are the methods the buffer makes possible.

MethodReturnsPurpose
readLine()String or nullOne line, terminator stripped; null at end
read()intOne character as an int, or -1 at end
mark(limit)voidRemember this position for up to limit chars
reset()voidRewind to the last mark
ready()booleanWhether a read can proceed without blocking

mark and reset are the pair that enable look-ahead; ready() lets you check for available input without blocking on a slow source.

import java.io.BufferedReader;
import java.io.StringReader;
import java.io.IOException;

public class Peek {
    public static void main(String[] args) throws IOException {
        try (BufferedReader br =
                 new BufferedReader(new StringReader("first
second"))) {
            br.mark(100);                     // remember the start
            String peek = br.readLine();      // look at line 1
            System.out.println("peeked:   " + peek);

            br.reset();                       // rewind to the mark
            String real = br.readLine();      // read line 1 again
            System.out.println("reread:   " + real);
        }
    }
}

Output:

peeked:   first
reread:   first

mark(100) records the position (the argument is how many characters may be read before the mark expires); reset() rewinds to it, so the same line is read twice. This look-ahead is impossible on a plain unbuffered reader, and it drives the header-detection example next.


Real World Example: Detecting An Optional Header With mark/reset

A CSV file may or may not start with a header row. The clean way to handle both is to peek at the first line: if it looks like a header (its first field is non-numeric), skip it; otherwise rewind and treat every line as data. This is exactly what mark/reset are for.

import java.io.BufferedReader;
import java.io.StringReader;
import java.io.IOException;

public class CsvSum {

    // Sums the first field of every data row, skipping a header if present.
    static int[] sum(String csv) throws IOException {
        int total = 0, rows = 0;
        try (BufferedReader br =
                 new BufferedReader(new StringReader(csv))) {
            br.mark(200);
            String firstLine = br.readLine();
            // If line 1 does not start with a digit, it is a header: skip it.
            if (firstLine != null
                    && !firstLine.isEmpty()
                    && !Character.isDigit(firstLine.charAt(0))) {
                // already past the header; fall through to read data
            } else {
                br.reset();                    // no header: rewind to line 1
            }
            String line;
            while ((line = br.readLine()) != null) {
                total += Integer.parseInt(line.trim());
                rows++;
            }
        }
        return new int[] { rows, total };
    }

    public static void main(String[] args) throws IOException {
        int[] withHeader = sum("count
10
20
30");
        int[] noHeader   = sum("10
20
30");

        System.out.println("with rows: " + withHeader[0]);
        System.out.println("with sum:  " + withHeader[1]);
        System.out.println("no rows:   " + noHeader[0]);
        System.out.println("no sum:    " + noHeader[1]);
    }
}

Output:

with rows: 3
with sum:  60
no rows:   3
no sum:    60

Both inputs produce the same three data rows summing to 60, which is the point: the routine handles a file with a header and a file without one identically, because it decides at runtime which case it is looking at. It marks the start, reads the first line to inspect it, and either keeps going (the header is already consumed) or rewinds to re-read line one as data. Without mark/reset you would have to open the source twice or buffer the whole thing yourself.

The look-ahead works only because the data is sitting in the buffer. mark(200) promises to remember the position as long as no more than 200 characters are read before the reset(); the buffer holds those characters, so rewinding is free. This is a capability the buffering enables, not just a speed optimisation -- an unbuffered reader has nowhere to rewind to, because it has not held onto anything.

The mark limit is the sharp edge here and worth understanding precisely. The argument is a read-ahead limit, not a byte offset: if you read past that many characters after marking, the mark is invalidated and reset() throws IOException. Setting it to a value large enough for your look-ahead -- one line, a few lines -- is fine; using it to rewind across a huge span is not what it is for, and a mark limit larger than the buffer can force the buffer to grow.

The honest limits go further. Buffering helps large reads, but for a handful of characters it is pure overhead -- an extra object and a copy for no trip saving, so a one-line read from System.in does not need it. readLine() also allocates a fresh String per line, so summing millions of numeric lines spends real time in garbage collection that a raw block scan would avoid. And there is a genuine design flaw to guard against: because BufferedReader wraps another reader, closing the BufferedReader closes the inner reader too -- convenient, but it means sharing one underlying stream between two wrappers and closing one wrapper pulls the stream out from under the other. Wrap once, close once, and do not layer two buffered readers over the same live source.


Common Mistakes

  1. Trying to pass a filename to BufferedReader. new BufferedReader("data.txt") does not compile -- the constructor takes a Reader, not a path. Wrap a reader: new BufferedReader(new FileReader("data.txt")).
  1. Forgetting the null check on readLine(). A loop that does not test readLine() against null either never ends or dereferences null. Use while ((line = br.readLine()) != null).
  1. Not closing the reader. An unclosed BufferedReader leaks the file handle of the reader it wraps. Declare it in a [[try-with-resources]] clause so both the wrapper and its inner reader close.
  1. Reading character by character from an unbuffered source. Reading straight from a FileReader one read() at a time pays the per-trip cost on every character. Wrap it in a BufferedReader so reads come from the buffer.
  1. Calling reset() without a valid mark(). reset() with no prior mark, or after reading past the mark's read-ahead limit, throws IOException. Mark first, and size the limit for how far you will look ahead.
  1. Misreading the mark argument as a byte offset. The number passed to mark(limit) is how many characters may be read before the mark expires, not a position. Set it to cover your look-ahead, not the file size.
  1. Buffering tiny inputs. Wrapping a one-line read in a BufferedReader adds an object and a copy for no trip saving. Reserve buffering for repeated or large reads where trips actually accumulate.
  1. Closing a shared inner stream twice. Layering two buffered readers over one underlying stream and closing one closes the shared stream, breaking the other. Wrap a source once and close it once.
  1. Assuming readLine() keeps the line terminator. readLine() strips the trailing `

or `, so code that expects the newline to be present mishandles the text. Add terminators back yourself if you need them.


Best Practices

  • Wrap the source, do not replace it. Construct a BufferedReader around a FileReader, InputStreamReader, or StringReader; the wrapper adds buffering while the inner reader supplies the data.
  • Always use try-with-resources. Declare the BufferedReader in a try (...) clause so it and the reader it wraps are closed on every exit path.
  • Buffer large or repeated reads. Reach for BufferedReader when reading big files or many lines, where amortising the per-trip cost across blocks is a real win.
  • Use the readLine() idiom. Read and test in one step -- while ((line = br.readLine()) != null) -- so the loop ends cleanly at end-of-input.
  • Size mark for your look-ahead. When peeking with mark/reset, pass a read-ahead limit large enough for the lines you inspect but no larger, so the buffer is not forced to grow needlessly.
  • Prefer mark/reset over re-opening. To inspect and then re-read the start of a source, mark and rewind rather than opening the source twice.
  • Skip buffering for trivial reads. For a single short read, use the underlying reader directly; the buffer's overhead buys nothing when there are no trips to save.
  • Wrap once over a shared stream. Do not layer multiple buffered readers over the same live source, since closing one closes the shared stream for all.

Practice Exercises

  1. The wrapping speed test. Build an in-memory source (a StringReader over many lines) and read it with a BufferedReader, counting the lines. Then explain, in a comment, why wrapping a FileReader in a BufferedReader reduces the number of trips to disk compared with reading the FileReader directly.
  1. The readLine loop. Write a BufferedReader loop using while ((line = br.readLine()) != null) over a multi-line String. Then describe what goes wrong if the != null check is removed -- both the never-terminating case and the null dereference.
  1. Peek and rewind. Using mark and reset, read the first line of a source to inspect it, then rewind and read it again as data. Print both reads to prove they return the same line, and set the mark limit large enough to cover one line.