FileReader Class in Java: Reading Text Files
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
BufferedReaderforreadLine(). - For binary files, use
FileInputStreaminstead.
2. FileReader Class Hierarchy
Swipe sideways to see the whole diagram.
3. Constructors of FileReader
| Constructor | Description |
|---|---|
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
| Method | Description |
|---|---|
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.
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);
}
}
currency -> INR max.cart.items -> 25 theme -> dark
How the code works
new FileReader(file, StandardCharsets.UTF_8)(Java 11) opens the file with an explicit charset.BufferedReaderaddsreadLine(), andstrip()removes surrounding spaces.- Lines starting with
#and empty lines are skipped; the rest are split at=. - A
TreeMapkeeps 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.
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);
}
}
Letters: 37, spaces: 8, lines: 3
How the code works
read(buffer)fills up to 16 characters and returns the actual countn.- Only the first
ncharacters are examined, because the last read is usually shorter. -1marks 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
BufferedReaderor an array. - Forgetting to close. Use try-with-resources.
- Using
FileReaderfor small files out of habit.Files.readString(path)reads the whole file in one line.
8. Java Version Improvements and Java 25 Updates
| Java version | Change |
|---|---|
| Java 1.1 | FileReader introduced, using the platform charset. |
| Java 11 | Constructors with a Charset; Files.readString(). |
| Java 18 | The default charset is UTF-8 everywhere (JEP 400). |
| Java 25 | No API changes. |
9. Summary
FileReaderreads characters from a text file.- Pass a
Charset(Java 11+) for predictable results. - Wrap it in a
BufferedReaderto read lines. - For small files,
Files.readString()is simpler.
Related Tutorials
- FileWriter Class in Java
- BufferedReader Class in Java
- FileInputStream Class in Java
- Files Class in Java (NIO.2)