FileReader Tutorial

The purpose of the FileReader class is to simply read character based files. The FileReader class implements AutoClosable so we can use the try-with-resources type exception handling. There are three overloaded constructors in the FileReader class, this tutorial will use only the one that takes a single parameter String value representing the file name. Regarding the other two constructors, I will revisit this class later once I have demonstrated the File and FileDescriptor classes. It also interesting to note that the FileReader class does not define or override any public methods, so it inherits all of its methods from its superclass InputStreamReader; InputStreamReader is a subclass of Reader which is a subclass of Object and that describes the class hierarchy.

FileReader(String filename)



Open the command prompt (CMD - see the Getting Started ) and type in the following commands.

C:\Windows\System32>cd \
C:\>md Java
C:\>cd Java
C:\Java>
C:\Java>md FR
C:\Java>cd FR
C:\Java\FR>Notepad Example.txt

Copy and Paste, or type the following code into Notepad and be sure to save the file when you are done.


First line of the text file.
Second line of the text file.
Third line of the text file.
Fourth line of the text file.
Fifth line of the text file.
C:\Java\FR>Notepad FR.java

Copy and Paste, or type the following code into Notepad and be sure to save the file when you are done.


import java.io.*;
class FR {
    public static void main(String args[]) {
        try (FileReader fr = new FileReader("Example.txt")) {
            int letters = fr.read();
            while(fr.ready()) {
                System.out.print((char) letters);
                letters = fr.read();
            }            
        } catch(IOException e) {
            System.out.println(e.getMessage());
        }
    }
}

Now switch back to the command prompt (CMD) and type in javac FR.java and press Enter.
Now type in java FR and press Enter.


C:\Java\FR>javac FR.java
C:\Java\FR>java FR
First line of the text file.
Second line of the text file.
Third line of the text file.
Fourth line of the text file.
Fifth line of the text file.


Final thoughts

Stay tuned to my next tutorial where I will wrap FileReader into a BufferedReader and we will gain more functionality.


Tutorials