00:00

Reader Class in Java: Reading Characters

Last updated:

Whether text comes from a file, a String, a web response or the keyboard, Java reads it through one abstract class: java.io.Reader. Code written for Reader works with every text source.

This tutorial covers what Reader is, its subclasses and methods, and two examples, including Reader.of(), added in Java 24.

1. What Is the Reader Class in Java?

Reader is the abstract superclass of all character input streams. It reads 16-bit char values instead of bytes. It was added in Java 1.1 and implements Readable and Closeable.

Subclasses must implement two methods: read(char[] cbuf, int off, int len) and close(). All other reading methods are built on them.

Declaration
public abstract class Reader implements Readable, Closeable

2. Reader Class Hierarchy

Reader hierarchy and methodsLeft: Reader, an abstract class implementing Readable and Closeable, with subclasses BufferedReader (extended by LineNumberReader), InputStreamReader (extended by FileReader), StringReader, CharArrayReader, PipedReader and FilterReader. Right: its methods grouped as read (read, read with arrays, read into a CharBuffer), move (skip, ready, mark, reset, markSupported) and copy and create (transferTo from Java 10, nullReader from Java 11, of from Java 24).Readerabstract class, implements Readable, CloseableBufferedReaderlines, bufferingLineNumberReaderline numbersInputStreamReaderbytes to charsFileReadera fileStringReadera StringCharArrayReadera char[]PipedReaderthreadsFilterReaderwrappersReadread(), read(char[])read(char[], off, len)read(CharBuffer) Java 5Moveskip(), ready()mark(), reset(), markSupported()Copy and createtransferTo(Writer) Java 10nullReader() Java 11of(CharSequence) Java 24

Swipe sideways to see the whole diagram.

3. Methods of the Reader Class

MethodDescription
int read()Next character (0–65535), or -1 at the end.
int read(char[] cbuf)Reads characters into an array; returns how many, or -1.
long skip(long n)Skips up to n characters.
boolean ready()Whether the next read is guaranteed not to block.
mark(int) / reset()Remember and return to a position, if markSupported() is true.
long transferTo(Writer out)Copies all remaining characters to a writer (Java 10).
static Reader nullReader()A reader with no characters (Java 11).
static Reader of(CharSequence cs)A reader over a String, StringBuilder or other sequence (Java 24).
void close()Releases the underlying resource.

4. Example: One Method for Every Text Source

A product review site counts words and lines. Because count() takes a Reader, the same method processes a string in memory and a file on disk.

WordStats.java
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;

public class WordStats {

    // Works with ANY Reader: a String, a file, a network response ...
    static int[] count(Reader in) throws IOException {
        int words = 0, lines = 0, c;
        boolean inWord = false;
        while ((c = in.read()) != -1) {
            if (c == '\n') lines++;
            if (Character.isLetterOrDigit(c)) {
                if (!inWord) words++;
                inWord = true;
            } else {
                inWord = false;
            }
        }
        return new int[] {words, lines};
    }

    public static void main(String[] args) throws IOException {
        String review = "Great phone.\nBattery lasts two days.\nCamera is average.\n";

        try (Reader fromString = new StringReader(review)) {
            int[] r = count(fromString);
            System.out.println("From a String: " + r[0] + " words, " + r[1] + " lines");
        }

        Path file = Files.createTempFile("review", ".txt");
        Files.writeString(file, review);
        try (Reader fromFile = Files.newBufferedReader(file, StandardCharsets.UTF_8)) {
            int[] r = count(fromFile);
            System.out.println("From a file:   " + r[0] + " words, " + r[1] + " lines");
        }
        Files.delete(file);
    }
}
Output
From a String: 9 words, 3 lines
From a file:   9 words, 3 lines

How the code works

  1. count() reads one character at a time until read() returns -1.
  2. A word starts whenever a letter or digit follows a non-letter, and each \n ends a line.
  3. StringReader and Files.newBufferedReader() supply the same text, so the results match.

5. Example: Reader.of() and transferTo()

A support tool drafts an email in a StringBuilder and copies it into a StringWriter, using methods from recent Java versions.

ReaderOfDemo.java
import java.io.IOException;
import java.io.Reader;
import java.io.StringWriter;

public class ReaderOfDemo {
    public static void main(String[] args) throws IOException {
        StringBuilder draft = new StringBuilder("Dear customer,\n");
        draft.append("your order #7781 has shipped.\n");

        StringWriter copy = new StringWriter();
        try (Reader in = Reader.of(draft)) {          // Java 24: a Reader over any CharSequence
            long chars = in.transferTo(copy);         // Java 10: copy every remaining char
            System.out.println("Characters copied: " + chars);
        }
        System.out.print(copy);
        System.out.println("nullReader is empty: " + (Reader.nullReader().read() == -1));   // Java 11
    }
}
Output
Characters copied: 45
Dear customer,
your order #7781 has shipped.
nullReader is empty: true

How the code works

  1. Reader.of(draft) (Java 24) creates a reader directly over the StringBuilder, with no copying into a String.
  2. transferTo(copy) (Java 10) copies all 45 characters to the writer and returns the count.
  3. Reader.nullReader() (Java 11) is an empty reader, useful as a safe default in tests.

6. Important Points

  • read() returns an int so that -1 can mean "end of stream".
  • read(char[]) may fill only part of the array; always use the returned count.
  • Readers decode bytes with a charset only when they wrap a byte stream, as InputStreamReader does.
  • Not every reader supports mark(); check markSupported().

7. Common Mistakes and Best Practices

  • Reading binary files with a Reader. Use InputStream for bytes.
  • Reading character by character from a file without buffering. Wrap it in a BufferedReader.
  • Forgetting to close file readers. Use try-with-resources.
  • Writing your own copy loop. Use transferTo().

8. Java Version Improvements and Java 25 Updates

Java versionChange
Java 1.1Reader introduced for character input.
Java 5Implements Readable; read(CharBuffer).
Java 10 and 11transferTo(Writer); nullReader().
Java 24Reader.of(CharSequence), standard in Java 25.

9. Summary

  • Reader is the abstract base class of every character input stream.
  • Code that accepts a Reader works with strings, files and network text.
  • read() returns a character or -1; array reads can be partial.
  • Java 10–24 added transferTo(), nullReader() and Reader.of().

Related Tutorials

10. Official Java Documentation References