Reader Class in Java: Reading Characters
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.
public abstract class Reader implements Readable, Closeable
2. Reader Class Hierarchy
Swipe sideways to see the whole diagram.
3. Methods of the Reader Class
| Method | Description |
|---|---|
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.
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);
}
}
From a String: 9 words, 3 lines From a file: 9 words, 3 lines
How the code works
count()reads one character at a time untilread()returns-1.- A word starts whenever a letter or digit follows a non-letter, and each
\nends a line. StringReaderandFiles.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.
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
}
}
Characters copied: 45 Dear customer, your order #7781 has shipped. nullReader is empty: true
How the code works
Reader.of(draft)(Java 24) creates a reader directly over theStringBuilder, with no copying into aString.transferTo(copy)(Java 10) copies all 45 characters to the writer and returns the count.Reader.nullReader()(Java 11) is an empty reader, useful as a safe default in tests.
6. Important Points
read()returns anintso that-1can 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
InputStreamReaderdoes. - Not every reader supports
mark(); checkmarkSupported().
7. Common Mistakes and Best Practices
- Reading binary files with a
Reader. UseInputStreamfor 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 version | Change |
|---|---|
| Java 1.1 | Reader introduced for character input. |
| Java 5 | Implements Readable; read(CharBuffer). |
| Java 10 and 11 | transferTo(Writer); nullReader(). |
| Java 24 | Reader.of(CharSequence), standard in Java 25. |
9. Summary
Readeris the abstract base class of every character input stream.- Code that accepts a
Readerworks with strings, files and network text. read()returns a character or-1; array reads can be partial.- Java 10–24 added
transferTo(),nullReader()andReader.of().
Related Tutorials
- Writer Class in Java
- Character Stream in Java
- BufferedReader Class in Java
- StringReader Class in Java