Tech and Media Labs
This site uses cookies to improve the user experience.




Java IO: FileReader

Jakob Jenkov
Last update: 2015-09-06

The Java FileReader class (java.io.FileReader) makes it possible to read the contents of a file as a stream of characters. It works much like the FileInputStream except the FileInputStream reads bytes, whereas the FileReader reads characters. The FileReader is intended to read text, in other words. One character may correspond to one or more bytes depending on the character encoding scheme.

FileReader Example

Here is a simple Java FileReader example:

Reader fileReader = new FileReader("c:\\data\\input-text.txt");

int data = fileReader.read();
while(data != -1) {
  //do something with data...
  doSomethingWithData(data);

  data = fileReader.read();
}
fileReader.close();

This example first creates a FileReader which is connected directly to the file pointed to by the file path passed as parameter to the FileReader constructor. Second, this example reads all characters one char at a time from the FileReader. Third, the FileReader is closed.

Note: The proper exception handling has been skipped here for the sake of clarity. To learn more about correct exception handling, go to Java IO Exception Handling.

read()

The read() method of the Java FileReader returns an int which contains the char value of the character read. If the read() method returns -1, there is no more data to read in the FileReader, and it can be closed. That is, -1 as int value, not -1 as byte value. There is a difference here!

FileReader Character Encoding

The Java FileReader assumes that you want to decode the bytes in the file using the default character encoding for the computer your application is running on. This may not always be what you want, and you cannot change it!

If you want to specify a different character decoding scheme, don't use a FileReader. Use an InputStreamReader on a FileInputStream instead. The InputStreamReader lets you specify the character encoding scheme to use when reading the bytes in the underlying file.

Closing a FileReader

When you are finished reading characters from a Java FileReader you should remember to close it. Closing a FileReader is done by calling its close() method. Here is how closing a Java FileReader looks:

fileReader.close();

You can also use the try-with-resources construct introduced in Java 7. Here is how to use and close a FileReader looks with the try-with-resources construct:

try(FileReader fileReader =
    new FileReader("c:\\data\\text.txt")){

    int data = fileReader.read();
    while(data != -) {
        System.out.print((char) data));
        data = fileReader.read();
    }
}

Notice how there is no longer any explicit close() method call to the FileReader instance. The try-with-resources construct takes care of that.

Jakob Jenkov




Copyright  Jenkov Aps
Close TOC