Java FileReader Class


In Java, the FileReader class is a convenient way to read the content of files. It is part of the java.io package and provides methods to read data as characters, making it useful for reading text-based files like .txt or .csv. In this guide, we will explore the features of the FileReader class, how to use it, and provide sample code for practical understanding.


What is Java FileReader Class?

The FileReader class is a subclass of InputStreamReader and provides a simple way to read files in Java. It reads characters from files and is best suited for reading text files. Unlike FileInputStream, which reads byte streams, FileReader reads data as characters, making it easier to work with character-based data like text, XML, JSON, etc.

Key Features of FileReader:

  • Reads files character by character.
  • Works only with character streams.
  • Can be used to read text files like .txt, .csv, and .json.
  • Supports Unicode and various encodings.

Syntax of FileReader Class

The FileReader class has two common constructors:

FileReader(String fileName) throws FileNotFoundException

This constructor creates a new FileReader object to read from the file specified by the file name.

FileReader(File file) throws FileNotFoundException

This constructor creates a FileReader object using the File object.


How to Use the FileReader Class

To effectively use the FileReader class in Java, you typically need to combine it with other classes like BufferedReader for efficient reading of lines from the file.

Example 1: Basic Usage of FileReader

In this example, we will show you how to read a text file character by character using FileReader.

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

public class FileReaderExample {
    public static void main(String[] args) {
        FileReader reader = null;

        try {
            // Create FileReader object
            reader = new FileReader("example.txt");

            // Read the file character by character
            int character;
            while ((character = reader.read()) != -1) {
                System.out.print((char) character);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // Close the FileReader
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Explanation:

  • We create a FileReader object and specify the file we want to read (example.txt).
  • The read() method reads one character at a time and returns an integer representing the character’s ASCII value.
  • The loop continues until the end of the file (indicated by -1).
  • Finally, the FileReader is closed using close() in the finally block to ensure proper resource management.

Using FileReader with BufferedReader

To read files more efficiently, we often use BufferedReader along with FileReader. BufferedReader reads large chunks of data into memory, making it much faster than reading one character at a time.

Example 2: Reading a File Line by Line

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

public class BufferedReaderExample {
    public static void main(String[] args) {
        FileReader reader = null;
        BufferedReader bufferedReader = null;

        try {
            // Create FileReader and BufferedReader objects
            reader = new FileReader("example.txt");
            bufferedReader = new BufferedReader(reader);

            String line;
            // Read the file line by line
            while ((line = bufferedReader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // Close the BufferedReader and FileReader
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Explanation:

  • BufferedReader is used to read the file line by line using readLine().
  • Each line is printed to the console, which is a more efficient way to read large files.

FileReader vs. FileInputStream

While both FileReader and FileInputStream can be used to read files in Java, they have key differences:

  1. FileReader: Designed for reading text files and works with character streams.
  2. FileInputStream: Used for reading binary data (like images, audio files, etc.) and works with byte streams.

Use FileReader when you are dealing with text data, and FileInputStream for binary data.


Exception Handling with FileReader

Since FileReader works with files, it may throw exceptions like FileNotFoundException or IOException. Proper exception handling is crucial for graceful error management.

Example 3: Exception Handling

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

public class FileReaderWithExceptionHandling {
    public static void main(String[] args) {
        try {
            // Trying to read a non-existing file
            FileReader reader = new FileReader("nonexistent.txt");
        } catch (FileNotFoundException e) {
            System.out.println("File not found: " + e.getMessage());
        } catch (IOException e) {
            System.out.println("Error while reading the file: " + e.getMessage());
        }
    }
}

Explanation:

  • This example demonstrates how to handle FileNotFoundException when the file does not exist.
  • If any other IO-related errors occur, they are caught by the IOException.

Best Practices When Using FileReader

  1. Close Resources: Always close the FileReader after use to free up system resources.
  2. Use BufferedReader: For efficient file reading, prefer using BufferedReader along with FileReader.
  3. Exception Handling: Properly handle exceptions to deal with issues like missing files or read/write errors.