Java BufferedReader
What BufferedReader Does
java.io.BufferedReader reads text from another character source — a file, a network connection, the console, a string — and adds two things:
- A buffer. Instead of fetching characters from the source one at a time, it reads a large block (8,192 characters by default) into memory and serves later requests from that block. Only when the buffer is empty does it go back to the source.
- Line reading. Its
readLine()method returns one complete line of text at a time, which is how most text files are processed.
BufferedReader doesn't read files by itself. It wraps another Reader — this is the decorator pattern used throughout java.io: each class adds one capability to the stream it wraps.
Reader source = new FileReader("cities.txt", StandardCharsets.UTF_8); // reads characters from a file
BufferedReader reader = new BufferedReader(source); // adds buffering and readLine()
Why Buffering Matters
Every read from a file goes through the operating system, and each such call has a fixed overhead regardless of how much data it returns. Reading a file one character per call means hundreds of thousands of calls; reading in 8 KB blocks means a handful. The program below counts how often the underlying source is actually called.
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
public class Count {
static class CountingReader extends FilterReader {
int calls = 0;
CountingReader(Reader in) { super(in); }
@Override public int read() throws IOException { calls++; return super.read(); }
@Override public int read(char[] buf, int off, int len) throws IOException { calls++; return super.read(buf, off, len); }
}
public static void main(String[] args) throws IOException {
Path file = Files.writeString(Path.of("big.txt"), "0123456789\n".repeat(10_000));
CountingReader direct = new CountingReader(new InputStreamReader(Files.newInputStream(file), StandardCharsets.UTF_8));
int chars = 0;
while (direct.read() != -1) chars++;
direct.close();
System.out.println("unbuffered: " + chars + " characters, " + direct.calls + " read calls on the source");
CountingReader source = new CountingReader(new InputStreamReader(Files.newInputStream(file), StandardCharsets.UTF_8));
int lines = 0;
try (BufferedReader buffered = new BufferedReader(source)) {
while (buffered.readLine() != null) lines++;
}
System.out.println("buffered: " + lines + " lines, " + source.calls + " read calls on the source");
}
}
Output:
unbuffered: 110000 characters, 110001 read calls on the source
buffered: 10000 lines, 15 read calls on the source
CountingReaderextendsFilterReader, a base class that passes every call through to the wrapped reader. It overrides the two read methods to count calls, so it shows exactly how often the reader beneath it is used.- Reading the 110,000-character file character by character makes 110,001 calls (the last one returns
-1, meaning end of input). - Wrapping the same source in a
BufferedReaderreduces that to 15 calls, because each one fetches up to 8,192 characters. On a real disk or network connection, that difference makes buffered reading many times faster.
This is why text files should practically always be read through a BufferedReader, or through Files methods that use one internally.
Creating a BufferedReader
// 1. Recommended for files: Files.newBufferedReader (UTF-8 by default)
BufferedReader a = Files.newBufferedReader(Path.of("cities.txt"));
BufferedReader b = Files.newBufferedReader(Path.of("legacy.csv"), StandardCharsets.ISO_8859_1);
// 2. Wrapping a FileReader (the charset constructor exists since Java 11)
BufferedReader c = new BufferedReader(new FileReader("cities.txt", StandardCharsets.UTF_8));
// 3. Wrapping any InputStream, such as the console or a network socket
BufferedReader d = new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8));
// 4. Reading from a String (useful in tests and parsers)
BufferedReader e = new BufferedReader(new StringReader("line 1\nline 2"));
// 5. Custom buffer size in characters
BufferedReader f = new BufferedReader(new FileReader("huge.log", StandardCharsets.UTF_8), 64 * 1024);
Files.newBufferedReader(path)is the simplest choice for files. It decodes UTF-8 unless you give another charset, and it reports invalid bytes withMalformedInputExceptioninstead of silently replacing them.new FileReader(name)without a charset uses the platform default encoding. Since Java 18 that is UTF-8 everywhere, but on Java 17 and earlier it differed by operating system, so always pass a charset toFileReaderin code that might run on older versions.InputStreamReaderconverts a byte stream into characters, which letsBufferedReaderread text from anything that produces bytes —System.in, aSocket, an HTTP response body, a ZIP entry.- The default buffer of 8,192 characters is right for almost all uses; a larger buffer rarely helps noticeably.
Closing the BufferedReader closes the reader it wraps, and that reader closes the file. So only the outermost object needs to go in try-with-resources.
Reading Lines with readLine
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
public class B1 {
public static void main(String[] args) throws IOException {
Files.writeString(Path.of("cities.txt"), "Chennai\nMadurai\r\nCoimbatore\n\nSalem");
try (BufferedReader reader = new BufferedReader(new FileReader("cities.txt", StandardCharsets.UTF_8))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println("[" + line + "] length " + line.length());
}
}
}
}
Output:
[Chennai] length 7
[Madurai] length 7
[Coimbatore] length 10
[] length 0
[Salem] length 5
How readLine() behaves:
- It returns the characters up to the next line terminator without the terminator.
\n(Unix),\r\n(Windows) and a lone\rare all recognised, soMaduraicomes back as 7 characters even though it was followed by\r\n. Files from any operating system can be read with the same code. - An empty line is returned as an empty string
"", notnull. - The last line doesn't need a terminator:
Salemis returned even though the file doesn't end with a newline. - At the end of the input it returns
null. The loopwhile ((line = reader.readLine()) != null)reads, assigns and tests in one condition.
Because only the current line is held in memory, this loop processes files of any size with constant memory usage. One caution: a "line" can be arbitrarily long. A file without line breaks (minified JSON, a corrupted log) is read into a single String, which can exhaust memory. When processing untrusted input, check line.length() or read in fixed-size chunks instead.
Other Reading Methods
import java.io.*;
import java.util.stream.Collectors;
public class B2 {
public static void main(String[] args) throws IOException {
String text = "id,name\n101,Asha\n102,Ravi\n103,Meena\n";
try (BufferedReader r = new BufferedReader(new StringReader(text))) {
char first = (char) r.read();
char[] buf = new char[6];
int n = r.read(buf, 0, buf.length);
System.out.println("read(): '" + first + "'");
System.out.println("read(buf): " + n + " chars -> \"" + new String(buf, 0, n).replace("\n", "\\n") + "\"");
System.out.println("readLine(): " + r.readLine());
System.out.println("skip(4): " + r.skip(4) + " -> rest of line: " + r.readLine());
System.out.println("lines(): " + r.lines().collect(Collectors.toList()));
System.out.println("at end: " + r.readLine() + " / " + r.read());
}
}
}
Output:
read(): 'i'
read(buf): 6 chars -> "d,name"
readLine():
skip(4): 4 -> rest of line: Asha
lines(): [102,Ravi, 103,Meena]
at end: null / -1
| Method | Returns | Notes |
|---|---|---|
read() | One character as an int, or -1 at the end | Returns int so that -1 can't be confused with a real character; cast to char after checking |
read(char[] buf, int off, int len) | The number of characters read into buf, or -1 | May read fewer than len characters; always use the returned count |
readLine() | The rest of the current line, or null | Here it returns "": read and read(buf) consumed id,name, so only the line terminator was left |
skip(n) | How many characters were actually skipped | Skipped 101,, so the rest of the line is Asha |
lines() | A lazy Stream<String> of the remaining lines (Java 8+) | Reads from the current position; closing the stream doesn't close the reader |
ready() | Whether a read is guaranteed not to block | Not a reliable "end of file" test — use readLine() == null or read() == -1 |
All the methods share the same position in the input. Each call continues exactly where the previous one stopped, whichever method it was.
mark and reset: Looking Ahead
Sometimes a parser has to read a line to decide whether it belongs to the current record, and if it doesn't, "put it back". mark(limit) remembers the current position, and reset() returns to it. The limit is the maximum number of characters you may read after marking while still being able to reset.
import java.io.*;
import java.util.*;
public class Mark {
record Message(String from, String subject, List<String> body) { }
// A header line starts with "From:"; every following line until the next header is body text
static List<Message> parse(BufferedReader r) throws IOException {
List<Message> result = new ArrayList<>();
String line;
while ((line = r.readLine()) != null) {
if (!line.startsWith("From: ")) continue;
String from = line.substring(6);
String subject = r.readLine().substring(9);
List<String> body = new ArrayList<>();
while (true) {
r.mark(1_000);
String next = r.readLine();
if (next == null) break;
if (next.startsWith("From: ")) {
r.reset();
break;
}
if (!next.isBlank()) body.add(next);
}
result.add(new Message(from, subject, body));
}
return result;
}
public static void main(String[] args) throws IOException {
String mbox = """
From: asha@gocourse.in
Subject: Java batch
Classes start Monday.
Bring a laptop.
From: ravi@gocourse.in
Subject: Fee receipt
Receipt attached.
""";
try (BufferedReader r = new BufferedReader(new StringReader(mbox))) {
parse(r).forEach(System.out::println);
}
}
}
Output:
Message[from=asha@gocourse.in, subject=Java batch, body=[Classes start Monday., Bring a laptop.]]
Message[from=ravi@gocourse.in, subject=Fee receipt, body=[Receipt attached.]]
How it works:
- The outer loop finds a
From:line and reads theSubject:line after it (substring(9)drops"Subject: "). - Before reading each possible body line, the inner loop calls
r.mark(1_000). - If the line read turns out to be the next message's
From:header,r.reset()moves the reader back to the marked position, so the outer loop's nextreadLine()reads that same header again. - Without mark/reset, the parser would consume the header while looking for the end of the body, and the second message would be lost.
The read-ahead limit must be at least as long as what you read after marking — here one line, which is far shorter than 1,000 characters. If you read past the limit, reset() may throw IOException: Mark invalid. markSupported() returns true for BufferedReader; many other readers don't support marking at all.
Practical Example: Parsing a Configuration File with Line Numbers
Reading line by line makes it easy to report where a problem is — essential for configuration files edited by hand. This loader reads an INI-style file with sections, comments and key = value settings.
import java.io.*;
import java.nio.file.*;
import java.util.*;
public class Ini {
static class ConfigException extends Exception {
ConfigException(Path file, int line, String problem) {
super(file.getFileName() + ":" + line + ": " + problem);
}
}
static Map<String, Map<String, String>> load(Path file) throws IOException, ConfigException {
Map<String, Map<String, String>> sections = new LinkedHashMap<>();
Map<String, String> current = null;
try (BufferedReader r = Files.newBufferedReader(file)) {
String raw;
int lineNo = 0;
while ((raw = r.readLine()) != null) {
lineNo++;
String line = raw.strip();
if (line.isEmpty() || line.startsWith("#") || line.startsWith(";")) continue;
if (line.startsWith("[")) {
if (!line.endsWith("]")) throw new ConfigException(file, lineNo, "unclosed section header");
String name = line.substring(1, line.length() - 1).strip();
current = sections.computeIfAbsent(name, k -> new LinkedHashMap<>());
continue;
}
int eq = line.indexOf('=');
if (eq <= 0) throw new ConfigException(file, lineNo, "expected key=value but found '" + line + "'");
if (current == null) throw new ConfigException(file, lineNo, "setting outside of any [section]");
current.put(line.substring(0, eq).strip(), line.substring(eq + 1).strip());
}
}
return sections;
}
public static void main(String[] args) throws IOException {
Path good = Files.writeString(Path.of("shop.ini"), """
# GOCOURSE shop settings
[server]
port = 8080
host = 0.0.0.0
[database]
url = jdbc:postgresql://db:5432/shop
pool.size = 10
""");
Path bad = Files.writeString(Path.of("broken.ini"), """
[server]
port = 8080
timeout 30
""");
for (Path p : List.of(good, bad)) {
try {
Map<String, Map<String, String>> cfg = load(p);
System.out.println(cfg);
int poolSize = Integer.parseInt(cfg.get("database").get("pool.size"));
System.out.println("pool size: " + poolSize);
} catch (ConfigException e) {
System.out.println("config error: " + e.getMessage());
}
}
}
}
Output:
{server={port=8080, host=0.0.0.0}, database={url=jdbc:postgresql://db:5432/shop, pool.size=10}}
pool size: 10
config error: broken.ini:3: expected key=value but found 'timeout 30'
Step by step:
- A line counter increases on every
readLine(), so every error can name the exact line, in thefile:line: messageformat that compilers and editors use. strip()removes leading and trailing whitespace (including Unicode spaces), so indentation and trailing spaces don't matter. Blank lines and lines starting with#or;are comments and are skipped.- Section headers like
[server]select the map that following settings go into.computeIfAbsentcreates the section's map the first time and reuses it if the same section appears again. - Settings are split at the first
=, so a value may itself contain=or:characters, as the JDBC URL does.eq <= 0rejects lines with no=and lines that start with=(an empty key). - Errors stop loading immediately with a checked
ConfigException, a custom exception (Custom Exceptions lesson) that callers must handle. Starting an application with a half-read configuration would be worse than not starting. LinkedHashMapkeeps sections and keys in file order, which makes the printed result easy to compare with the file.
Real projects usually use an existing format with a library (Properties files, YAML with SnakeYAML, or a framework's configuration support), but the technique — read line by line, track the line number, validate each line and fail with a precise message — is the same one those libraries use internally.