JavaFileReader

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

Java FileReader Class

Java FileReader class is used to read data from the file. It returns data in byte format like FileInputStream class.

It is character-oriented class which is used for file handling in java.

Java FileReader class declaration

Let's see the declaration for Java.io.FileReader class:

  1. public class FileReader extends InputStreamReader  

Constructors of FileReader class

Constructor

Description

FileReader(String file)

It gets filename in string. It opens the given file in read mode. If file doesn't exist, it throws FileNotFoundException.

FileReader(File file)

It gets filename in file instance. It opens the given file in read mode. If file doesn't exist, it throws FileNotFoundException.

 

Methods of FileReader class

Method

Description

int read()

It is used to return a character in ASCII form. It returns -1 at the end of file.

void close()

It is used to close the FileReader class.

Java FileReader Example

In this example, we are reading the data from the text file testout.txt using Java FileReader class.

  1. package com.javatpoint;  
  2.   
  3. import java.io.FileReader;  
  4. public class FileReaderExample {  
  5.     public static void main(String args[])throws Exception{    
  6.           FileReader fr=new FileReader("D:\testout.txt");    
  7.           int i;    
  8.           while((i=fr.read())!=-1)    
  9.           System.out.print((char)i);    
  10.           fr.close();    
  11.     }    
  12. }    

Here, we are assuming that you have following data in "testout.txt" file:

Welcome to tutorialtours.

Output:

Welcome to tutorialtours.