FileReader Java


FileReader is a character stream reading character by character from a file.

Note: Before reading this tutorial, it is advised to know Java I/O Streams – Overview.

FileReader is equivalent to FileInputStream of byte streams.

The following example reads character by character from file wishes.txt.
import java.io.*;
public class FRDemo
{
  public static void main(String args[]) throws IOException
  {
    FileReader fr = new FileReader("wishes.txt");

    int temp;
    while((temp = fr.read()) != -1)
    {
      System.out.print((char)temp);
    }

    fr.close();
  }
}

FileReader JavaOutput Screenshot on FileReader Java

FileReader fr = new FileReader(“wishes.txt”);

The hard disk file wishes.txt to read is passed to FileReader constructor.

while((temp = fr.read()) != -1)
{
System.out.print((char)temp);
}

The read() method of FileReader reads at a time one byte from wishes.txt and returns it as an int. The character read is assigned to temp variable so that it can be used in other part of the code. It is used in the loop to print the character at command prompt. But each character read is converted to int by read() method. So it is to be converted back to character and is done in the loop as (char) temp.

fr.close();

When the job of reading is over, the FileReader stream is to be closed to free the memory occupied by fr object. When closed, the object fr is ready for garbage collection.

A similar program is available at
File Copying FileReader FileWriter reading a file and writing to another file.

The same file copying can be done using byte streams of FileInputStream and FileOutputStream and is discussed in File Copy Tutorial Java.

Leave a Comment

Your email address will not be published.