Overview of FileReader Class
The FileReader class extends the InputStreamReader class and is specifically designed for reading character-based data from a file. It is an ideal choice when working with text files and allows for efficient reading of characters from a file. To use the FileReader class, you need to create an instance of it and provide the file path as a parameter. This establishes a connection between the file reader object and the specified file, enabling you to read characters from it.Java FileReader Example
Let's look at an example that demonstrates how to use the FileReader class to read the contents of a file:
// We import the necessary classes: `java.io.BufferedReader`
import java.io.BufferedReader;
// We import the class: `java.io.FileReader` here to use fileReader
import java.io.FileReader;
// We import the class: `java.io.IOException` here to handle fileReader exception
import java.io.IOException;
public class FileReaderExample {
public static void main(String[] args) {
String filePath = "/path/to/example.txt";
try (FileReader fileReader = new FileReader(filePath);
BufferedReader bufferedReader = new BufferedReader(fileReader)) {
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("Error reading file: " + e.getMessage());
}
}
}
Pseudocode explanation:
- Import the necessary classes: BufferedReader, FileReader, and IOException.
- Define a class named FileReaderExample.
- Inside the main method, we declare a String variable named filePath and assign it the absolute path to the "example.txt" file on the system.
- Use a try-with-resources statement to automatically close the FileReader and BufferedReader instances when we're done using them.
- Inside the try block, create a FileReader object, passing the filePath to its constructor.
- Create a BufferedReader object, passing the FileReader object as its argument, which allows us to read the file line by line efficiently.
- Declare a String variable named line to store each line of the file.
- Enter a loop that continues as long as the line is not null.
- Inside the loop, read a line from the file using the readLine method of the bufferedReader object.
- If the line is not null, print it to the console using System.out.println().
- If any exception occurs during file reading, catch it in the catch block and print an error message.
Output
This is line 1.
This is line 2.
This is line 3.
Note:
The program reads each line from the "example.txt" file (specified by the filePath variable) and prints it to the console. If any error occurs while reading the file, it will display an error message. Make sure to replace "/path/to/example.txt" with the actual absolute path to the "example.txt" file on your system for the code to work properly.
GO TO FULL VERSION