Java Reader Class
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.
InputStream | Reader | |
|---|---|---|
| Unit | byte (8 bits) | char (16-bit UTF-16 code unit) |
read() returns | 0–255, or -1 | 0–65535, or -1 |
| Bulk read into | byte[] | char[] (or CharBuffer) |
| Use for | Binary data | Text |
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,82in one andB9,9,9in 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. InputStreamReaderkeeps 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
| Method | Behaviour |
|---|---|
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 anint; casting tocharafter checking for-1gives the character.read(buf),skipandtransferTobehave like theirInputStreamcounterparts, but count characters: after readingabcand skippingde, the remainingfghis copied into aStringWriter.charisn't always a whole character. A Javacharis a UTF-16 code unit. Characters outside the Basic Multilingual Plane — most emoji, some rare CJK characters, historic scripts — need twochars, a surrogate pair."Hi 👋"has 5chars but 4 real characters (code points).Reader.read()returns the two halves separately (U+D83D,U+DC4B), so code that processes onecharat a time must handle surrogates — or work with code points viaString.codePoints()orCharacter.toCodePoint(high, low).LineNumberReaderis aBufferedReaderthat counts lines, useful for error messages that point to a line.
The Reader Family
| Class | Reads characters from | Notes |
|---|---|---|
InputStreamReader | Any InputStream, decoded with a charset | The bridge from bytes to characters. Always pass the charset |
FileReader | A file | An InputStreamReader over a FileInputStream. Charset constructors since Java 11 |
StringReader | A String | Ideal for tests and for parsing text already in memory |
CharArrayReader | A char[] | |
BufferedReader | Another reader | Buffering and readLine() (BufferedReader lesson) |
LineNumberReader | Another reader | Line counting |
PushbackReader | Another reader | unread() characters — "look ahead" for parsers |
FilterReader | Another reader | Base class for your own decorators |
PipedReader | A PipedWriter in another thread | Thread-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:
- Any
Readeras input. The constructor accepts aReader, 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 aBufferedReader) and wraps everything in aPushbackReader. - Peeking with
unread. At the start ofnextRecord, one character is read to detect the end of input and then pushed back withunread(c), so the main loop reads it again.PushbackReaderhas a one-character pushback buffer by default, which is all this parser needs. - A small state machine. The
quotedflag 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. - 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). - Line endings. CSV files usually use
\r\n(the text block above includes\rexplicitly). After\r, an optional\nis consumed, so\r\n,\nand a lone\rare all treated as one line break. - Empty fields (
Meena,,) produce empty strings, so every record keeps its 3 columns. - 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.