Core Java Tutorial

Core Java Tutorial

How to Read file Using FileReader in Java

FileReader

FileReader class for reading character files, It can read any file char by char.

Example

import java.io.File;

import java.io.FileReader;

import java.io.IOException;

public class FileReaderExample {

 public static void main(String[] args) {


  File f1 = new File("sam.txt");


  try {

   FileReader fr = new FileReader(f1);

   long s = 0; // starting point of file

   long e = f1.length(); // find total char in a file

   while (s < e) {

    char c = (char) fr.read(); // read a char using read() method

    System.out.print(c);

    s++;

   }

  } catch (IOException e) {

   // TODO Auto-generated catch block

   e.printStackTrace();

  }


 }

}
Before executing the above program make sure you have a sam.txt file in current directory.
The above program will print all lines in a file to a console.