The Java FileReader class is utilized for reading data from files and it provides data in byte format similar to the FileInputStream class.
This is a class that operates on characters and is utilized for managing files in Java.
Java FileReader class declaration
Now, let's examine the declaration of the Java.io.FileReader class:
Example
public class FileReader extends InputStreamReader
Constructors of FileReader class
| Constructor | Description |
|---|---|
| FileReader(String file) | It gets filename instring. It opens the given file in read mode. If file doesn't exist, it throws FileNotFoundException. |
| FileReader(File file) | It gets filename infileinstance. 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 instance, we are retrieving information from the text document named testout.txt by utilizing the Java FileReader class.
Example
package com.example;
import java.io.FileReader;
public class FileReaderExample {
public static void main(String args[])throws Exception{
FileReader fr=new FileReader("D:\\testout.txt");
int i;
while((i=fr.read())!=-1)
System.out.print((char)i);
fr.close();
}
}
In this scenario, it is presumed that the data is available in the file named "testout.txt":
Example
Welcome to Java.
Output:
Output
Welcome to Java.