Java - FileReader Class


This class inherits from the InputStreamReader class. FileReader is used for reading streams of characters.

This class has several constructors to create required objects. Below given are the list of constructors provided by the FileReader class.

SR.NO Constructors and Description
1 FileReader(File file)

This constructor creates a new FileReader, given the File to read from.

2 FileReader(FileDescriptor fd)

This constructor creates a new FileReader, given the FileDescriptor to read from.

3 FileReader(String fileName)

This constructor creates a new FileReader, given the name of the file to read from.

Once you have FileReader object in hand then there is a list of helper methods which can be used manipulate the files

SR.NO Methods with Description
1 public int read() throws IOException

Reads a single character. Returns an int, which represents the character read.

2 public int read(char [] c, int offset, int len)

Reads characters into an array. Returns the number of characters read.


Following is the example to demonstrate class:


public class FileRead{

   public static void main(String args[])throws IOException{

      File file = new File("Hello1.txt");
      // creates the file
      // creates a FileWriter Object
      FileWriter writer = new FileWriter(file); 
      // Writes the content to the file
      writer.write("This\n is\n an\n example\n"); 

      //Creates a FileReader Object
      FileReader fr = new FileReader(file); 
      char [] a = new char[50];; // reads the content to the array
      for(char c : a)
          System.out.print(c); //prints the characters one by one

This would produce the following result: