Java FileReader Class tutorial with Examples

The FileReader class in Java is used to read character-based data from files.

It is part of the java.io package and allows you to read data from a file character by character, line by line, or into an array.

FileReader is especially useful for reading text files, as it can handle files with character data efficiently.

In this tutorial, we will cover:

Let’s explore each topic with examples.

1. Basic Usage of FileReader

The FileReader class has constructors to open a file and prepare it for reading.

If the file does not exist, it throws a FileNotFoundException.

Example 1: Reading a File with FileReader

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

public class BasicFileReaderExample {
    public static void main(String[] args) {
        try {
            // Create a FileReader instance to read "example.txt"
            FileReader reader = new FileReader("example.txt");

            // Read each character until the end of the file
            int character;
            while ((character = reader.read()) != -1) {
                System.out.print((char) character);
            }

            // Close the FileReader
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  • Explanation: This example reads the file example.txt character by character. The read() method returns the ASCII integer value of each character, which is then cast to char for display. When it reaches the end, it returns -1.

2. Reading a File Character by Character

Reading character by character can be helpful when processing text data in a specific format or when looking for specific characters within the file.

Example 2: Reading Character by Character

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

public class ReadCharacterByCharacterExample {
    public static void main(String[] args) {
        try (FileReader reader = new FileReader("characters.txt")) {
            int charData;
            while ((charData = reader.read()) != -1) {
                System.out.print((char) charData);  // Print each character
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  • Explanation: Here, we use a while loop to read each character until the end of the file (-1). The file is closed automatically with the try-with-resources statement.

3. Reading a File into a Character Array

FileReader can read data into a character array, which is more efficient than reading one character at a time, especially for larger files.

Example 3: Reading a File into a Character Array

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

public class ReadIntoCharArrayExample {
    public static void main(String[] args) {
        try (FileReader reader = new FileReader("example.txt")) {
            // Create a character array to store data
            char[] buffer = new char[100];
            int numCharsRead;

            // Read characters into the buffer array
            while ((numCharsRead = reader.read(buffer)) != -1) {
                System.out.print(new String(buffer, 0, numCharsRead));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  • Explanation: In this example, data is read into a buffer array. The read(buffer) method returns the number of characters read into the buffer, which may be less than the array length if the file ends early.

4. Using BufferedReader with FileReader for Line-by-Line Reading

For efficient line-by-line reading, use BufferedReader with FileReader.

BufferedReader provides the readLine() method, which reads a line of text as a string.

Example 4: Reading a File Line by Line

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

public class BufferedReaderExample {
    public static void main(String[] args) {
        try (FileReader reader = new FileReader("example.txt");
             BufferedReader bufferedReader = new BufferedReader(reader)) {

            String line;
            while ((line = bufferedReader.readLine()) != null) {
                System.out.println(line);  // Print each line
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  • Explanation: BufferedReader reads one line at a time using readLine(), which is more efficient for text files than reading character by character. It stops reading when readLine() returns null, indicating the end of the file.

5. Handling Exceptions and Closing FileReader

Always close FileReader after reading, either explicitly by calling close() or using try-with-resources for automatic closure, which prevents memory leaks.

Example 5: Reading a File with try-with-resources

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

public class TryWithResourcesFileReaderExample {
    public static void main(String[] args) {
        // Use try-with-resources to automatically close FileReader
        try (FileReader reader = new FileReader("resources.txt")) {
            int data;
            while ((data = reader.read()) != -1) {
                System.out.print((char) data);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  • Explanation: This example uses try-with-resources to automatically close the FileReader once reading is complete, ensuring that resources are released.

Summary of Key FileReader Concepts

Feature Description
Basic Reading Reads a file character by character; read() returns -1 when end of file is reached.
Character Array Reading Reads multiple characters into a buffer array for efficient processing.
Line-by-Line Reading Use BufferedReader with FileReader to read files line by line.
Exception Handling Handles IOException and uses try-with-resources for automatic resource management.

Conclusion

In this tutorial, we covered various ways to use the FileReader class in Java:

  • Basic reading with FileReader character by character.
  • Reading data into a character array for efficient processing.
  • Reading files line by line using BufferedReader.
  • Using try-with-resources to manage resources automatically.

Related posts

Java FileWriter Class Tutorial with Examples

Java Directory Management Tutorial with Examples

Deleting Files in Java: A Comprehensive Tutorial with Code Examples