FileReader Class in Java

The FileReader class creates a Reader that you can use to read the contents of a file. FileReader is meant for reading streams of characters. For reading streams of raw bytes, consider using a FileInputStream.

FileReader Constructors

  • FileReader(File file) - Creates a new FileReader, given the File to read from.
  • FileReader(FileDescriptor fd) - Creates a new FileReader, given the FileDescriptor to read from.
  • FileReader(String fileName) - Creates a new FileReader, given the name of the file to read from.

FileReader Class Methods

  • int read() - It is used to return a character in ASCII form. It returns -1 at the end of a file.
  • void close() - It is used to close the FileReader class.

FileReader Class Example

The following example shows how to read lines from a file and display them on the standard output device. It reads its own source file, which must be in the current directory. This example uses the try-with-resources statement to close the resources automatically.
import java.io.FileReader;
import java.io.IOException;

/**
 * The class demonstrate the usage of FileReader class methods.
 * @author javaguides.net
 *
 */
class FileReaderDemo {
 public static void main(String args[]) {
  try (FileReader fr = new FileReader("FileReaderDemo.java")) {
   int c;
   // Read and display the file.
   while ((c = fr.read()) != -1)
    System.out.print((char) c);
  } catch (IOException e) {
   System.out.println("I/O Error: " + e);
  }
 }
}
Note that this program reads its own source file, which must be in the current directory and produces below output:
package com.javaguides.javaio.book;

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

class FileReaderDemo {
 public static void main(String args[]) {
  try (FileReader fr = new FileReader("FileReaderDemo.java")) {
   int c;
   // Read and display the file.
   while ((c = fr.read()) != -1)
    System.out.print((char) c);
  } catch (IOException e) {
   System.out.println("I/O Error: " + e);
  }
 }
}

Reference

Comments