| Lesson 14 | The FileReader class |
| Objective | Explore the Java FileReader class for Java I/O |
You have already learned how to chain an InputStreamReader to a FileInputStream for reading text files. While this approach gives you full control over character encoding and buffer sizing, Java provides FileReader as a convenience class that handles these details automatically using platform defaults.
The FileReader class extends InputStreamReader and is specifically designed for reading character files. It simplifies file reading by automatically using your platform's default character encoding (such as UTF-8 on most modern systems) and a standard buffer size.
java.lang.Object
â³ java.io.Reader
â³ java.io.InputStreamReader
â³ java.io.FileReader
Important limitation: If you need to specify a different character encoding or adjust the buffer size, you should construct an InputStreamReader on a FileInputStream instead. FileReader is meant for reading streams of characters; for reading streams of raw bytes, use FileInputStream.
The FileReader class provides three constructors that differ only in how you specify the file to read:
public FileReader(String fileName) throws FileNotFoundException
public FileReader(File file) throws FileNotFoundException
public FileReader(FileDescriptor fd)
File object, useful when you've already constructed a File instanceNote that only constructors are declared in the FileReader class itself. All reading operations use methods inherited from Reader, including read(), ready(), and close().
Here's a basic example that reads a file character by character:
try {
FileReader fr = new FileReader("36.html");
while (true) {
int i = fr.read();
if (i == -1) break; // End of file
char c = (char) i;
// Process character...
}
fr.close();
} catch (IOException e) {
System.err.println(e);
}
In this example, read() returns an integer representing the character read, or -1 when the end of the file is reached. Remember to close the FileReader when finished, or use a try-with-resources statement for automatic resource management:
try (FileReader fr = new FileReader("36.html")) {
int i;
while ((i = fr.read()) != -1) {
char c = (char) i;
// Process character...
}
} catch (IOException e) {
System.err.println(e);
}
FileReader is ideal for simple text file reading when the default character encoding is appropriate. For more control over encoding or performance tuning, use InputStreamReader with FileInputStream. For reading raw binary data, use FileInputStream directly.
Available since: JDK 1.1
See Also: InputStreamReader, FileInputStream, FileWriter