filereader-used-for-reading-file-in-java-File-handling

admin

2/27/2025

        FileReader in Java: A Complete Guide with Examples

Go Back

FileReader in Java: A Complete Guide with Examples

Updated: February 13, 2025 by Shubham mishra

Introduction to FileReader in Java

The FileReader class in Java is part of the java.io package and is used to read data from files. It is a convenient way to read character-based data from a file, such as text files. In this tutorial, we will explore how to use the FileReader class with practical examples and best practices.

            FileReader in Java: A Complete Guide with Examples

Key Features of FileReader

  • Character-Based Reading: FileReader reads data character by character, making it ideal for text files.
  • Simple to Use: It provides a straightforward API for reading files.
  • Exception Handling: Proper error handling is essential when working with files to avoid runtime errors.

Example 1: Reading a File Character by Character

The following example demonstrates how to read a file character by character using the FileReader class:


import java.io.*;

class FileExample3 {
    public static void main(String args[]) {
        FileReader fr = null;
        try {
            fr = new FileReader("D:/Assignments/message.txt");
            int ch;
            while ((ch = fr.read()) != -1) {
                System.out.print((char) ch);
            }
        } catch (FileNotFoundException fnf) {
            System.out.println("Cannot open the file");
        } catch (IOException ex) {
            System.out.println("Error while reading file");
        } finally {
            if (fr != null) {
                try {
                    fr.close();
                } catch (IOException ex) {
                    System.out.println("Error while closing file");
                }
            }
        }
    }
}

In this example:

  • FileReader is used to open the file message.txt.
  • The read() method reads one character at a time until the end of the file (-1 is returned).
  • Proper exception handling is implemented to manage file-related errors.

Example 2: Reading an Entire File into a String

The following example shows how to read an entire file into a string using the FileReader class:


import java.io.*;

class FileExample3 {
    public static void main(String args[]) {
        FileReader fr = null;
        try {
            fr = new FileReader("D:/Assignments/message.txt");
            File fobj = new File("D:/Assignments/message.txt");
            int sz = (int) fobj.length();
            char[] arr = new char[sz];
            fr.read(arr);
            String s = new String(arr);
            System.out.println(s);
        } catch (FileNotFoundException fnf) {
            System.out.println("Cannot open the file");
        } catch (IOException ex) {
            System.out.println("Error while reading file");
        } finally {
            if (fr != null) {
                try {
                    fr.close();
                } catch (IOException ex) {
                    System.out.println("Error while closing file");
                }
            }
        }
    }
}

In this example:

  • The File class is used to determine the size of the file.
  • A character array is created to store the file's contents.
  • The read() method reads the entire file into the array, which is then converted to a string.

Best Practices for Using FileReader

  • Always Close the File: Use a finally block or try-with-resources to ensure the file is closed after reading.
  • Handle Exceptions: Properly handle FileNotFoundException and IOException to avoid runtime errors.
  • Use Buffered Readers: For better performance, wrap FileReader in a BufferedReader.

Conclusion

The FileReader class in Java is a powerful tool for reading character-based data from files. By following the examples and best practices outlined in this tutorial, you can efficiently handle file operations in your Java applications. As you progress, consider exploring advanced topics like BufferedReader, FileWriter, and Java's NIO package for more robust file handling.

Practice coding regularly, work on small projects, and explore Java's extensive standard library to become proficient in file handling. Best of luck on your coding journey!

 

Table of content