00:00

FileReader Class in Java: Reading Text Files

Last updated:

Configuration files, CSV exports, logs and templates are plain text. FileReader is the classic java.io class for reading characters from such a file.

This tutorial covers its constructors, its methods and two practical examples.

1. What Is FileReader in Java?

FileReader is a convenience subclass of InputStreamReader that opens a file and decodes its bytes into characters. It was added in Java 1.1.

  • Since Java 11 you can pass a Charset; without one, it uses the default charset (UTF-8 since Java 18).
  • It reads characters, not lines; wrap it in a BufferedReader for readLine().
  • For binary files, use FileInputStream instead.

2. FileReader Class Hierarchy

FileReader class hierarchyFileReader extends InputStreamReader, which extends the abstract class Reader and Object. It implements Readable, Closeable and AutoCloseable. Modern alternatives are Files.newBufferedReader, Files.readString and Files.readAllLines.ObjectextendsReaderabstract classextendsInputStreamReaderdecodes bytesextendsFileReaderreads text from a fileReadableCloseableAutoCloseableimplementsModern alternativesFiles.newBufferedReader()Files.readString()Files.readAllLines()

Swipe sideways to see the whole diagram.

3. Constructors of FileReader

ConstructorDescription
FileReader(String fileName) / FileReader(File file)Opens the file with the default charset.
FileReader(String fileName, Charset charset)Opens the file with an explicit charset (Java 11).
FileReader(File file, Charset charset)The same, for a File object (Java 11).
FileReader(FileDescriptor fd)Reads from an already open file.

The String and File constructors throw FileNotFoundException if the file is missing, a directory or unreadable.

4. Commonly Used Methods

MethodDescription
int read()Next character, or -1 at the end of the file.
int read(char[] cbuf)Fills an array; returns how many characters were read.
long transferTo(Writer out)Copies the rest of the file to a writer (Java 10).
void close()Closes the file.

5. Example: Loading a Configuration File

An online shop reads its settings from a simple key = value file, skipping blank lines and comments.

ConfigLoader.java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
import java.util.TreeMap;

public class ConfigLoader {
    public static void main(String[] args) throws IOException {
        Path config = Files.createTempFile("app", ".conf");
        Files.writeString(config, "# shop settings\ncurrency = INR\nmax.cart.items = 25\n\ntheme = dark\n");

        Map<String, String> settings = new TreeMap<>();
        try (BufferedReader in = new BufferedReader(new FileReader(config.toFile(), StandardCharsets.UTF_8))) {
            String line;
            while ((line = in.readLine()) != null) {
                line = line.strip();
                if (line.isEmpty() || line.startsWith("#")) continue;   // skip blanks and comments
                int eq = line.indexOf('=');
                settings.put(line.substring(0, eq).strip(), line.substring(eq + 1).strip());
            }
        }
        settings.forEach((k, v) -> System.out.println(k + " -> " + v));
        Files.delete(config);
    }
}
Output
currency -> INR
max.cart.items -> 25
theme -> dark

How the code works

  1. new FileReader(file, StandardCharsets.UTF_8) (Java 11) opens the file with an explicit charset.
  2. BufferedReader adds readLine(), and strip() removes surrounding spaces.
  3. Lines starting with # and empty lines are skipped; the rest are split at =.
  4. A TreeMap keeps the settings sorted by key.

6. Example: Counting Characters with a Buffer

A writing app reports statistics for a short poem. It reads 16 characters at a time into an array.

PoemStats.java
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;

public class PoemStats {
    public static void main(String[] args) throws IOException {
        Path poem = Files.createTempFile("poem", ".txt");
        Files.writeString(poem, "Rain on the roof,\nchai in my cup,\nmonday can wait.\n");

        int letters = 0, spaces = 0, lines = 0;
        char[] buffer = new char[16];                       // read 16 characters at a time
        try (Reader in = new FileReader(poem.toFile(), StandardCharsets.UTF_8)) {
            int n;
            while ((n = in.read(buffer)) != -1) {           // n = how many chars were read
                for (int i = 0; i < n; i++) {
                    char c = buffer[i];
                    if (Character.isLetter(c)) letters++;
                    else if (c == ' ') spaces++;
                    else if (c == '\n') lines++;
                }
            }
        }
        System.out.println("Letters: " + letters + ", spaces: " + spaces + ", lines: " + lines);
        Files.delete(poem);
    }
}
Output
Letters: 37, spaces: 8, lines: 3

How the code works

  1. read(buffer) fills up to 16 characters and returns the actual count n.
  2. Only the first n characters are examined, because the last read is usually shorter.
  3. -1 marks the end of the file.

7. Common Mistakes and Best Practices

  • Using the constructor without a charset on Java 17 or earlier. The result depended on the operating system.
  • Reading one character at a time from large files. Use a BufferedReader or an array.
  • Forgetting to close. Use try-with-resources.
  • Using FileReader for small files out of habit. Files.readString(path) reads the whole file in one line.

8. Java Version Improvements and Java 25 Updates

Java versionChange
Java 1.1FileReader introduced, using the platform charset.
Java 11Constructors with a Charset; Files.readString().
Java 18The default charset is UTF-8 everywhere (JEP 400).
Java 25No API changes.

9. Summary

  • FileReader reads characters from a text file.
  • Pass a Charset (Java 11+) for predictable results.
  • Wrap it in a BufferedReader to read lines.
  • For small files, Files.readString() is simpler.

Related Tutorials

10. Official Java Documentation References