Java.io - SPLessons

Java.io FileReader

Chapter 18

SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Java.io FileReader

Java.io FileReader

shape Introduction

Java.io FileReader is the class used for reading content of files in characters. Java.io FileReader having the feature to read streams of characters into the file or directory. Whereas for the purpose of reading bytes of stream, FileInputStream is used.

The default character encoding scheme is only possible in case of Java.io FileReader. To specify a different character encoding scheme then use InputStreamReader.

shape Conceptual
figure

The function of reader object related with all types of readers is shown in above figure.

Class Declaration

shape Declaration

Java.io.FileReader class is declared as shown below:

Public class FileReader extends InputStreamReader

shape Fields

Java.io FileReader class fields are as follows:

  • Protected Object lock : For synchronize operations this object is used in FileReader.

Class Constructors

shape Table

Constructor Description
FileReader(File file) The function of this constructor is to construct the file reader object and reads the given file.
FileReader(FileDescriptor file) The function of this constructor is to construct the file reader object and reads the given file descriptor.
FileReader(String fileName) This constructor creates a new FileReader and given the name of the file to read from.The function of this constructor is to construct the file reader object and reads the given file name.

Inherited Methods

shape Description

From the following classes methods are inherited to Java.io.FileReader are:

  • Java.io.InputStreamReader
  • java.uti.Reader
  • Java.io.Object


shape Example


FileRead.java

import java.io.*;
public class FileRead {

   public static void main(String args[])throws IOException {
      File file = new File("Hello1.txt");
      
      // creates the file
      file.createNewFile();
      
      // creates a FileWriter Object
      FileWriter writer = new FileWriter(file); 
      
      // Writes the content to the file
      writer.write("Splessons\nThis\n is\n an\n example\n"); 
      writer.flush();
      writer.close();

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

Output
The result will be as follows.

Splessons
This
 is
 an
 example

Summary

shape Key Points

  • Java.io FileReader is the class used for reading content of files in characters.
  • FileReader having the feature to read streams of characters into the file or directory.
  • The default character encoding scheme is only possible in case of FileReader. To specify a different character encoding scheme then use InputStreamReader.