Introduction
We will be heading towards multiple ways of reading and writing a text file. There are several ways to read a text file in Java, e.g., you can use BufferedReader, FileReader, or Scanner class to read a text file. Every class provides something special, e.g., BufferedReader provides buffering of data for fast reading, while Scanner provides parsing ability.
Java FileReader Class
Java FileReader class is used to read the data from the File. It returns data in byte format like FileInputStream class.
It is a character-oriented class that is used for file handling in Java.
Declaration:
public class FileReader extends InputStreamReader
Constructors in this class are as follows:
- FileReader(File file): It creates a new FileReader, given the File to read from
- FileReader(FileDescriptor fd): It creates a new FileReader, given the FileDescriptor to read from
- FileReader(String fileName): It creates a new FileReader, given the name of the File to read from
Example:
import java.io.FileReader;
public class Example {
public static void main(String args[])throws Exception{
FileReader f=new FileReader("D:\\readout.txt");
int i;
while((i=f.read())!=-1)
System.out.print((char)i);
f.close();
}
}
Here, we are assuming that you have the following data in the "readout.txt" file:
Hello Coders
Output
Hello Coders
Also see, Duck Number in Java