FileReader: Reading Text Files Character by Character
What you'll learn: How FileReader provides a convenient way to read text files as character streams instead of raw bytes.
The Character-Aware File Reader
When you need to read text from a file, FileReader is your go-to class. While FileInputStream forces you to deal with raw bytes (and worry about character encoding), FileReader automatically handles the conversion from bytes to characters using the platform's default character encoding.
Think of FileReader as a translator that sits between your file and your program. It reads the bytes from disk and converts them into Java char values, so you can work directly with readable text instead of numeric byte values.
How FileReader Works
FileReader is a concrete subclass of Reader, which means it inherits all the standard character-stream methods you've learned: read(), read(char[]), skip(), and close().
Creating a FileReader:
FileReader reader = new FileReader("example.txt");
Reading characters one at a time:
int charValue = reader.read(); // Returns -1 at end of file
if (charValue != -1) {
char c = (char) charValue;
}
Reading into a character array:
char[] buffer = new char[1024];
int charsRead = reader.read(buffer);
When to Use FileReader
Use FileReader when you're reading plain text files and the default character encoding is acceptable. It's simpler than manually wrapping FileInputStream with InputStreamReader. However, remember that FileReader uses the platform's default encoding—if you need explicit encoding control (like UTF-8), you'll want InputStreamReader instead (a future topic).
Key Takeaway: FileReader simplifies reading text files by automatically converting bytes to characters using the default encoding, eliminating the need to manually handle byte-to-char conversion.