Java BufferedReader

Su Suriya Ravichandran Updated 18 Nov 2026
11 min read ·Lesson 141 of 306

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:

  1. 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.
  2. 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
  • CountingReader extends FilterReader, 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 BufferedReader reduces 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 with MalformedInputException instead 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 to FileReader in code that might run on older versions.
  • InputStreamReader converts a byte stream into characters, which lets BufferedReader read text from anything that produces bytes — System.in, a Socket, 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 \r are all recognised, so Madurai comes 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 "", not null.
  • The last line doesn't need a terminator: Salem is returned even though the file doesn't end with a newline.
  • At the end of the input it returns null. The loop while ((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
MethodReturnsNotes
read()One character as an int, or -1 at the endReturns 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 -1May read fewer than len characters; always use the returned count
readLine()The rest of the current line, or nullHere it returns "": read and read(buf) consumed id,name, so only the line terminator was left
skip(n)How many characters were actually skippedSkipped 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 blockNot 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:

  1. The outer loop finds a From: line and reads the Subject: line after it (substring(9) drops "Subject: ").
  2. Before reading each possible body line, the inner loop calls r.mark(1_000).
  3. 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 next readLine() reads that same header again.
  4. 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:

  1. A line counter increases on every readLine(), so every error can name the exact line, in the file:line: message format that compilers and editors use.
  2. 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.
  3. Section headers like [server] select the map that following settings go into. computeIfAbsent creates the section's map the first time and reuses it if the same section appears again.
  4. Settings are split at the first =, so a value may itself contain = or : characters, as the JDBC URL does. eq <= 0 rejects lines with no = and lines that start with = (an empty key).
  5. 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.
  6. LinkedHashMap keeps 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.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java BufferedReader and get answers drawn from it.

Signed-in readers only.