Java Reader Class

Su Suriya Ravichandran Updated 18 Nov 2026
9 min read ·Lesson 155 of 306

What Reader Is

java.io.Reader is the abstract base class for reading characters. It's the text counterpart of InputStream: where an InputStream delivers bytes, a Reader delivers char values.

InputStreamReader
Unitbyte (8 bits)char (16-bit UTF-16 code unit)
read() returns0–255, or -10–65535, or -1
Bulk read intobyte[]char[] (or CharBuffer)
Use forBinary dataText

Files and network connections only store and transmit bytes, so text has to be decoded with a charset at some point. Readers do that decoding — or, for in-memory sources like StringReader, start from characters directly. Code that processes text should work with a Reader so that it never has to deal with bytes and encodings itself.

Why Not Decode Bytes Yourself?

It's tempting to read bytes in chunks and turn each chunk into a String. That breaks as soon as the text contains characters that take more than one byte:

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;

public class Split {
    public static void main(String[] args) throws IOException {
        byte[] utf8 = "Price ₹99".getBytes(StandardCharsets.UTF_8);
        System.out.println(utf8.length + " bytes: " + Arrays.toString(utf8));

        StringBuilder wrong = new StringBuilder();
        try (InputStream in = new ByteArrayInputStream(utf8)) {
            byte[] chunk = new byte[4];
            int n;
            while ((n = in.read(chunk)) != -1) {
                wrong.append(new String(chunk, 0, n, StandardCharsets.UTF_8));
            }
        }
        System.out.println("decoding byte chunks: " + wrong);

        StringBuilder right = new StringBuilder();
        try (Reader in = new InputStreamReader(new ByteArrayInputStream(utf8), StandardCharsets.UTF_8)) {
            char[] chunk = new char[4];
            int n;
            while ((n = in.read(chunk)) != -1) {
                right.append(chunk, 0, n);
            }
        }
        System.out.println("InputStreamReader:    " + right);
    }
}

Output:

11 bytes: [80, 114, 105, 99, 101, 32, -30, -126, -71, 57, 57]
decoding byte chunks: Price ��99
InputStreamReader:    Price ₹99
  • The rupee sign is three bytes in UTF-8 (-30, -126, -71, i.e. E2 82 B9).
  • Reading 4 bytes at a time splits those three bytes across two chunks: e, space, E2, 82 in one and B9, 9, 9 in the next. Neither half is a valid character on its own, so each is decoded as the replacement character �. The bug only appears for non-ASCII text, and only when a character happens to fall on a chunk boundary — which is why it often slips through testing.
  • InputStreamReader keeps incomplete byte sequences between reads and only produces a character when all its bytes have arrived, so the result is always correct.

The Reader Methods

MethodBehaviour
int read()Next character as an int, or -1 at the end
int read(char[] buf) / int read(char[] buf, int off, int len)Reads up to len characters; returns how many, or -1
int read(CharBuffer target)Reads into an NIO CharBuffer
long skip(long n)Skips characters
boolean ready()Whether the next read is guaranteed not to block
void mark(int limit) / void reset() / boolean markSupported()Remember and return to a position, if supported
long transferTo(Writer out) (Java 10+)Copies all remaining characters to a Writer
Reader.nullReader() (Java 11+)An empty reader
void close()Releases the underlying resource

A subclass must implement read(char[], int, int) and close(); the other methods are built on top of them.

import java.io.*;

public class R1 {
    public static void main(String[] args) throws IOException {
        try (Reader r = new StringReader("Java I/O")) {
            int c;
            StringBuilder sb = new StringBuilder();
            while ((c = r.read()) != -1) {
                sb.append((char) c).append('|');
            }
            System.out.println(sb);
        }

        try (Reader r = new StringReader("abcdefgh")) {
            char[] buf = new char[3];
            System.out.println("read(buf) -> " + r.read(buf) + " chars: " + new String(buf));
            System.out.println("skip(2)   -> " + r.skip(2));
            StringWriter rest = new StringWriter();
            System.out.println("transferTo -> " + r.transferTo(rest) + " chars: " + rest);
        }

        String text = "Hi 👋";
        System.out.println("length " + text.length() + ", code points " + text.codePointCount(0, text.length()));
        try (Reader r = new StringReader(text)) {
            int c;
            while ((c = r.read()) != -1) {
                System.out.printf("U+%04X%s ", c, Character.isSurrogate((char) c) ? "(surrogate)" : "");
            }
            System.out.println();
        }
        text.codePoints().forEach(cp -> System.out.printf("U+%04X ", cp));
        System.out.println();

        try (LineNumberReader lnr = new LineNumberReader(new StringReader("first\nsecond\nthird"))) {
            String line;
            while ((line = lnr.readLine()) != null) System.out.println(lnr.getLineNumber() + ": " + line);
        }
        System.out.println("nullReader: " + Reader.nullReader().read());
    }
}

Output:

J|a|v|a| |I|/|O|
read(buf) -> 3 chars: abc
skip(2)   -> 2
transferTo -> 3 chars: fgh
length 5, code points 4
U+0048 U+0069 U+0020 U+D83D(surrogate) U+DC4B(surrogate) 
U+0048 U+0069 U+0020 U+1F44B 
1: first
2: second
3: third
nullReader: -1
  • read() returns each character as an int; casting to char after checking for -1 gives the character.
  • read(buf), skip and transferTo behave like their InputStream counterparts, but count characters: after reading abc and skipping de, the remaining fgh is copied into a StringWriter.
  • char isn't always a whole character. A Java char is a UTF-16 code unit. Characters outside the Basic Multilingual Plane — most emoji, some rare CJK characters, historic scripts — need two chars, a surrogate pair. "Hi 👋" has 5 chars but 4 real characters (code points). Reader.read() returns the two halves separately (U+D83D, U+DC4B), so code that processes one char at a time must handle surrogates — or work with code points via String.codePoints() or Character.toCodePoint(high, low).
  • LineNumberReader is a BufferedReader that counts lines, useful for error messages that point to a line.

The Reader Family

ClassReads characters fromNotes
InputStreamReaderAny InputStream, decoded with a charsetThe bridge from bytes to characters. Always pass the charset
FileReaderA fileAn InputStreamReader over a FileInputStream. Charset constructors since Java 11
StringReaderA StringIdeal for tests and for parsing text already in memory
CharArrayReaderA char[]
BufferedReaderAnother readerBuffering and readLine() (BufferedReader lesson)
LineNumberReaderAnother readerLine counting
PushbackReaderAnother readerunread() characters — "look ahead" for parsers
FilterReaderAnother readerBase class for your own decorators
PipedReaderA PipedWriter in another threadThread-to-thread text pipes

The standard way to read text from a byte source:

Reader reader = new BufferedReader(new InputStreamReader(byteStream, StandardCharsets.UTF_8));

For files, Files.newBufferedReader(path, charset) creates the same chain in one call.

Practical Example: A Real CSV Parser

Splitting a line on commas (line.split(",")) breaks on real CSV files, where fields can be quoted to contain commas, quotes (written as "") and even line breaks. A correct parser has to read character by character and sometimes look one character ahead — exactly what a Reader and a PushbackReader provide.

import java.io.*;
import java.util.*;

public class Csv {
    static class CsvFormatException extends IOException {
        CsvFormatException(int line, String message) { super("record starting on line " + line + ": " + message); }
    }

    private final PushbackReader in;
    private int line = 1;

    Csv(Reader source) {
        this.in = new PushbackReader(source instanceof BufferedReader ? source : new BufferedReader(source));
    }

    /** Returns the next record, or null at the end of the input. */
    List<String> nextRecord() throws IOException {
        int c = in.read();
        if (c == -1) return null;
        in.unread(c);

        int startLine = line;
        List<String> fields = new ArrayList<>();
        StringBuilder field = new StringBuilder();
        boolean quoted = false;
        while (true) {
            c = in.read();
            if (quoted) {
                if (c == -1) throw new CsvFormatException(startLine, "unterminated quoted field");
                if (c == '"') {
                    int next = in.read();
                    if (next == '"') {
                        field.append('"');                 // "" inside quotes is a literal quote
                    } else {
                        quoted = false;
                        if (next != -1) in.unread(next);
                    }
                } else {
                    if (c == '\n') line++;
                    field.append((char) c);
                }
            } else if (c == '"' && field.isEmpty()) {
                quoted = true;
            } else if (c == ',') {
                fields.add(field.toString());
                field.setLength(0);
            } else if (c == '\r' || c == '\n' || c == -1) {
                if (c == '\r') {
                    int next = in.read();
                    if (next != '\n' && next != -1) in.unread(next);
                }
                if (c != -1) line++;
                fields.add(field.toString());
                return fields;
            } else {
                field.append((char) c);
            }
        }
    }

    public static void main(String[] args) throws IOException {
        String data = """
            name,city,comment\r
            Asha Rao,Chennai,"Paid, thanks"\r
            "Kumar ""KR"" R",Coimbatore,"Line one
            line two"\r
            Meena,,\r
            """;
        Csv csv = new Csv(new StringReader(data));
        List<String> record;
        while ((record = csv.nextRecord()) != null) {
            System.out.println(record.size() + " fields: " + record);
        }

        try {
            Csv bad = new Csv(new StringReader("id,note\n1,\"never closed\n"));
            while (bad.nextRecord() != null) { }
        } catch (CsvFormatException e) {
            System.out.println("CsvFormatException: " + e.getMessage());
        }
    }
}

Output:

3 fields: [name, city, comment]
3 fields: [Asha Rao, Chennai, Paid, thanks]
3 fields: [Kumar "KR" R, Coimbatore, Line one
line two]
3 fields: [Meena, , ]
CsvFormatException: record starting on line 2: unterminated quoted field

How the parser works:

  1. Any Reader as input. The constructor accepts a Reader, so the same parser reads from a file (Files.newBufferedReader), an upload (new InputStreamReader(stream, UTF_8)) or a test string. It adds buffering (unless it's already a BufferedReader) and wraps everything in a PushbackReader.
  2. Peeking with unread. At the start of nextRecord, one character is read to detect the end of input and then pushed back with unread(c), so the main loop reads it again. PushbackReader has a one-character pushback buffer by default, which is all this parser needs.
  3. A small state machine. The quoted flag records whether the parser is inside a quoted field. Outside quotes, a comma ends a field and a line break ends the record. Inside quotes, commas and line breaks are ordinary characters — that's how "Paid, thanks" stays one field and "Line one\nline two" spans two lines.
  4. Escaped quotes need lookahead. Inside quotes, a " is either the end of the field or the first half of "" (a literal quote). The parser reads the next character to decide; if it isn't another ", it pushes it back so the outer logic sees it (normally a comma or line break).
  5. Line endings. CSV files usually use \r\n (the text block above includes \r explicitly). After \r, an optional \n is consumed, so \r\n, \n and a lone \r are all treated as one line break.
  6. Empty fields (Meena,,) produce empty strings, so every record keeps its 3 columns.
  7. Error reporting. The line counter is increased at every line break, including breaks inside quoted fields. When the input ends inside quotes, the exception reports the line where the broken record started, which is what someone fixing the file needs.

Because the parser reads one character at a time, it uses constant memory and can process files of any size. For production use, established libraries (Apache Commons CSV, OpenCSV, Jackson's CSV module) handle more variations — other separators, comments, header mapping — but they're built on exactly this kind of Reader-based loop.

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 Reader Class and get answers drawn from it.

Signed-in readers only.