The FileReader class in Java is a part of the java.io
package and is widely used for reading character files. Whether you’re building a simple file-processing utility or working on a larger application, understanding the FileReader class is crucial for efficient file handling.
This blog post covers the basics of the FileReader class, its methods, and how to use it effectively in your Java programs.
What is the FileReader Class?
The FileReader class is a character stream reader designed specifically for reading text files. It is a subclass of the InputStreamReader class and is best suited for reading data in character form, such as .txt
files.
Syntax and Constructor
Here’s how you can create an instance of the FileReader class:
FileReader fr = new FileReader(String fileName);
Constructor Variants
FileReader(String fileName)
: Accepts the name of the file as a string.FileReader(File file)
: Accepts aFile
object representing the file.
Example: Reading a File Using FileReader
Here’s a simple example of reading the contents of a text file using the FileReader class:
import java.io.FileReader;
import java.io.IOException;
public class FileReaderExample {
public static void main(String[] args) {
try (FileReader fr = new FileReader("example.txt")) {
int character;
while1 != -1) {
System.out.print((char) character);
}
} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
}
}
}
Explanation:
fr.read()
: Reads one character at a time and returns its integer ASCII value.(char) character
: Converts the ASCII value to its corresponding character.- Try-with-resources: Automatically closes the FileReader after use.
Key Methods of FileReader
read()
: Reads a single character.read(char[] cbuf)
: Reads characters into an array.close()
: Closes the FileReader, freeing system resources.
Best Practices
- Always use a try-with-resources block to handle file closing automatically.
- For reading large files, consider using a BufferedReader with FileReader for better performance.
Conclusion
The Java FileReader class is an essential tool for reading character files. With its simple API and integration with other stream classes, it’s perfect for straightforward text file processing. Try the examples above to get started with file handling in Java!
- character = fr.read( [↩]