Java FileReader: Read Text Files

You can use the following steps to read a txt file using FileReader:

  1. Importing necessary packages: import java.io.FileReader;
  2. 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”);
  3. Create a character array to store the read data: char[] buffer = new char[1024];
  4. 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);
  5. While looping through the character array, continue until the read character count is -1, indicating the end of the file has been reached.
  6. 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).
  7. 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.

bannerAds