FileReader

FileReader is a character-based class in the java.io package used to read data from files as characters (not bytes). It is mainly used for reading text files.

Commonly Used Constructors and Methods

Simple Program

Mahesh has a file data.txt that contains a simple message. He wants to read the contents and display them on the console using FileReader.

import java.io.FileReader;
import java.io.IOException;

public class FileReaderExample {
    public static void main(String[] args) {
        try (FileReader fr = new FileReader("data.txt")) {
            int ch;
            while ((ch = fr.read()) != -1) {
                System.out.print((char) ch);
            }
        } catch (IOException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

Content of data.txt:

Hello LotusJavaPrince!

Output:

Hello LotusJavaPrince!

FileReader is ideal for reading text files where character encoding is important.

  • It simplifies working with character data compared to FileInputStream.
  • For line-by-line reading, it’s commonly used with BufferedReader.
  • It is not suitable for binary files — for that, FileInputStream should be used.
Scroll to Top