Reading Writing Text  «Prev  Next»


Lesson 14The FileReader class
ObjectiveInvestigate the Java FileReader class.

Java FileReader Class

You havae already learned how to chain an OutputStreamWriter to a FileOutputStream and an InputStreamReader to a FileInputStream. Although this is not hard, Java provides two utility classes that take care of the details, java.io.FileWriter and java.io.FileReader.
We will look at FileReader in this lesson and examine FileWriter in the next lesson.
The FileReader class reads text files using the platform's default character encoding and the default buffer size. If you need to change the encoding and/or buffer size, construct an InputStreamReader on a FileInputStream instead.
There are three FileReader constructors.
Only the constructors are declared in this class. You use the standard Reader methods like read(), ready(), and close() to actually read the data in the file.

try {
  FileReader fr = new FileReader("36.html");
  while (true) {
    int i = fr.read();
    if (i == -1) break;
    // ...
  }
}
catch (IOException e) {
  System.err.println(e);
} 

FileReader

The FileReader class is a subclass of InputStreamReader that reads text files using the platform's default character encoding. If you need to change the encoding, construct an InputStreamReader chained to a FileInputStream instead.
public class FileReader extends InputStreamReader

This class has three constructors that differ only in how the file to be read is specified:
public FileReader(String fileName) throws FileNotFoundException
public FileReader(File file) throws FileNotFoundException
public FileReader(FileDescriptor fd)

Only the constructors are declared in this class. You use the standard Reader methods like read(), ready(), and close() to read the text in the file. For example:
try {
 FileReader fr = new FileReader("36.html");
  while (true) {
    int i = fr.read();
    if (i == -1) break;
      // ...
    }
  }
catch (IOexception e) { 
  System.err.println(e); 
 }