File Reader

Class FileReader

java.lang.Object
  extended by java.io.Reader
      extended by java.io.InputStreamReader
          extended by java.io.FileReader

All Implemented Interfaces:

By using FileReader we can read character data from file.

Constructors: 

1. FileReader fr=new FileReader(String name);
/* Creates a new FileReader, given the name of the file to read from */

2. FileReader fr=new FileReader(File f);
/* Creates a new FileReader, given the File to read from*/

3. FileReader fr=new FileReader(FileDescriptor fd);
/* Creates a new FileReader, given the FileDescriptor to read from */

Method Summary
 
Methods inherited from class java.io.InputStreamReader
 
Methods inherited from class java.io.Reader
 
Methods inherited from class java.lang.Object

Most Frequently Used Methods: 

1. int read() throws IOException : It attempts to read next character from the file, if it is available it returns UNICODE and if it is not available then this method returns -1

2. int read (char[] ch) throws IOException : To read characters and place it into a char[]. This method returns no of characters read from the file to the char[].

3. void close() : Closes the stream and releases any system resources associated with it.

Now lets check the methods usage with an example 

package com.java.everythingaboutselenium;
import java.io.File;
import java.io.IOException;

class FileReaderDemo
{
public static void main(String[] args)
{
      File f=new File("FileReaderDemo.txt");
      FileReader fr=new FileReader(f);
      System.out.println(fr.read());
      /* This print the UNICODE of the first character */

      char[] ch=new char[(int)(f.length())];
      fr.read(ch);
     /*File Data copied to Array */
      for (char c1:ch)
     {
         System.out.println(c1);
      }
      FileReader fr1=new FileReader(f);
      int i=fr1.read();
      while(i!=-1)
     {
         System.out.println((char)i);
         i=fr1.read();
      }
}