Java FileReader Class

Category: Java   Tags: Java, Java File Handling, Java Character Stream, Java Reader Class, Java FileReader Class

The FileReader class creates a Reader and used to read the content of a file. It has below declaration:

                                    public class FileReader
                                    extends InputStreamReader
                                

Constructors

public FileReader(File file) throws FileNotFoundException
Creates a new FileReader. file is the given the File to read from. Throws FileNotFoundException if the file does not exist.
public FileReader(String fileName) throws FileNotFoundException
Creates a new FileReader. fileName is the given the file name to read from. Throws FileNotFoundException if the file does not exist.
public FileReader(FileDescriptor fd) throws FileNotFoundException
Creates a new FileReader by using the file descriptor fd, which represents an existing connection to an actual file in the file system.

Here is a simple Java program for FileReader. This program will read the file content character by character:

FileReaderExample.java

                            package com.tutorial.java.files;

                            import java.io.FileReader;
                            import java.io.IOException;

                            public class FileReaderExample {

                                public static void main(String[] args) throws IOException {
                                    FileReader reader = null;
                                    try {
                                        reader = new FileReader("sample.txt");
                                        int c;
                                        while ((c = reader.read()) != -1) {
                                            System.out.print((char) c);
                                        }
                                    } catch (IOException e) {
                                        // handle error
                                    } finally {
                                        if(reader != null)
                                            reader.close();
                                    }

                                }
                            }