Java FileReader Example

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 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);
  }
 }
}

Comments