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

Reading Characters with read() Methods

Master the read() method variants: single character, character array, and array with offset and length.

Reading Characters with read() Methods

You'll learn: how to read text data from a FileReader using three variants of the read() method, each suited to different reading strategies.

The Three read() Variants

When reading text with FileReader, you have three options that mirror the byte stream methods but work with characters instead:

1. read() – Single Character

FileReader reader = new FileReader("data.txt");
int ch = reader.read();  // Returns -1 at end-of-file
if (ch != -1) {
    char character = (char) ch;
    // Process the character
}
reader.close();

Reads one character at a time. Returns an int (the Unicode value), or -1 when the file ends. You cast to char to use it as a character.

2. read(char[]) – Fill Entire Array

FileReader reader = new FileReader("data.txt");
char[] buffer = new char[1024];
int charsRead = reader.read(buffer);  // Returns count or -1
// buffer now contains 'charsRead' characters
reader.close();

Tries to fill the entire array with characters. Returns the actual number of characters read, which may be less than the array size near file end.

3. read(char[], int offset, int length) – Partial Array Read

FileReader reader = new FileReader("data.txt");
char[] buffer = new char[1024];
int charsRead = reader.read(buffer, 100, 500);
// Reads up to 500 characters into buffer starting at position 100
reader.close();

Reads up to length characters and places them starting at offset in the array. Useful when you need fine control over where data lands.

Analogy

Think of these like filling a cup: read() is a tiny espresso cup (one sip), read(char[]) fills a whole mug to the brim, and read(char[], offset, length) fills only the middle section of a pitcher.

Key Takeaway: Use read() for character-by-character processing, read(char[]) for bulk reading into a buffer, and read(char[], int, int) when you need precise control over buffer positioning.