Java program to read contents of a file using FileReader

FileReader class in Java : Write a Java program to read from a file using FileReader:

Using ‘FileReader’ class, we can read contents of a file. Using this class, we can read the contents as a stream of characters. In this tutorial, I will show you one simple example to use ‘FileReader’ class in Java .

Constructors :

‘FileReader’ has three different constructors :

FileReader(File file) :

For this constructor, you need to pass a file object . The FileReader will read from that file. On any error, it will throw an exception ‘FileNotFoundException’.

FileReader(String fileName) :

Instead of sending a ‘File’ object, we can also send the name of the file to read from. It throws same type of exception as above ‘FileNotFoundException’

FileReader(FileDescriptor fd) :

This constructor takes one ‘FileDescriptor’ object to the constructor.

How to read from a file :

After ‘FileReader’ object is created, we can read from a file using read() method. This method reads character by character from the file . Actually it returns an int which contains the char value . After the reading is completed, it returns a ‘-1’.

Closing a FileReader :

After reading is completed, we should always close the ‘FileReader’ using close() method call.

Following example shows you how to read contents from a file using ‘FileReader’ in Java :

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

/**
 * Example class for FileReader
 */
public class ExampleClass {

    //utility method to print a char
    static void print(char value) {
        System.out.print(value);
    }


    public static void main(String[] args) {
        readFile();
    }

    static void readFile() {

        try {
            //create a FileReader Object by providing File name in the constructor
            FileReader reader = new FileReader("C://sample.txt");

            int c; //this will contain the character value as int

            while ((c = reader.read()) != -1) {
                print((char) c);
            }

            //close the reader after reading is completed
            reader.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        }


    }
}

This program will print the contents of the file ‘sample.txt’ . So, we have first constructed one ‘FileReader’ object by providing the file name to it and then start reading using ‘read()’ method until it becomes ‘-1’. Each time , we have printed out the char value for that int . After reading is completed, we closed the reader using ‘close()’ method.

Similar tutorials :