Course contentsShow
← Java
Lesson 1962 of 2,87040. File I/O: Character StreamsFree lesson

Reader's Core Methods: read(), read(char[]), and skip()

Exploring the fundamental methods for reading characters, including single-character and buffer-based reading.

Reader's Core Methods: read(), read(char[]), and skip()

You'll learn the essential methods every Reader subclass provides for reading characters one at a time, in batches, or by skipping ahead in the stream.

Understanding Reader's API

Just as InputStream provided methods for reading bytes, the abstract Reader class provides parallel methods for reading characters. These methods handle character encoding automatically, so you work with char values instead of raw bytes.

The Three Core Reading Methods

read() — Single Character Reading

The read() method returns one character as an int, or -1 if the end of the stream is reached:

int ch = reader.read(); // returns 0-65535 or -1
if (ch != -1) {
    char character = (char) ch;
}

Notice the parallel to InputStream.read(), but here the returned value represents a Unicode character, not a byte.

read(char[]) — Buffer-Based Reading

The read(char[]) method fills a character array and returns the number of characters actually read:

char[] buffer = new char[1024];
int charsRead = reader.read(buffer);
// buffer now contains up to 1024 characters

This is far more efficient than reading one character at a time, just like byte arrays improved byte stream performance.

skip(long) — Jumping Ahead

The skip(long n) method attempts to skip over n characters in the stream, returning the actual number skipped:

long skipped = reader.skip(100); // skip up to 100 chars

Useful when you need to jump to a specific position without reading intermediate data.

The Pattern

These methods mirror InputStream's API but operate on characters instead of bytes, automatically handling character encoding behind the scenes.

Key Takeaway: Reader provides read() for single characters, read(char[]) for efficient batch reading, and skip() for advancing through the stream—the character-based equivalents of byte stream operations.