Java FileReader: Read Text Files
You can use the following steps to read a txt file using FileReader:
- Importing necessary packages: import java.io.FileReader;
- Create a FileReader object and pass the path of the txt file you want to read as a parameter: FileReader reader = new FileReader(“file path”);
- Create a character array to store the read data: char[] buffer = new char[1024];
- Use the read() method to read data from a txt file and store it in a character array, then return the number of characters read: int length = reader.read(buffer);
- While looping through the character array, continue until the read character count is -1, indicating the end of the file has been reached.
- In a loop, you can manipulate the data that is read as needed, such as printing it to the console using System.out.println(buffer).
- Close the FileReader object: reader.close();
The complete sample code is shown below:
import java.io.FileReader;
import java.io.IOException;
public class FileReaderExample {
public static void main(String[] args) {
FileReader reader = null;
try {
reader = new FileReader("path/to/file.txt");
char[] buffer = new char[1024];
int length;
while ((length = reader.read(buffer)) != -1) {
System.out.println(buffer);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Please replace “file path” with the actual path to the txt file.