FileReader Class
In this tutorial, we are going to discuss about FileReader Class in java. The FileReader
class in Java, found in the java.io
package, is used to read character data from a file. It provides a convenient way to read characters from a file as a stream of characters.
This class can be used for reading character data from the file. It is not recommended to use the FileInputStream class if we have to read any textual information as these are Byte stream classes.
Constructors
FileReader fr = new FileReader(String name);
FileReader fr = new FileReader(File f);
Important methods
1. int read():
For reading next character from the file. If there is no next character this method returns -1
2. int read(char[] ch):
To read data from the file into char array.
3. void close():
To close FileReader
E.g
package com.ashok.files;
import java.io.File;
import java.io.FileReader;
/**
*
* @author ashok.mariyala
*
*/
public class MyFile {
public static void main(String arg[]) throws Exception {
File f = new File("Ashok.txt");
FileReader fr = new FileReader(f);
System.out.println(fr.read());
char[] ch2 = new char[(int) (f.length())];
System.out.println(ch2.length);
fr.read(ch2);
for (char ch1 : ch2) {
System.out.print(ch1);
}
}
}
Output
97
40
Hai
How are you
abcaHai
How are you
abc
The usage of FileReader and FileWriter is in efficient because
- While writing the data by using FileWriter, program is responsible to insert line separators manually.
- We can read the data character by character only by using FileReader. If increases the number of I/O operations and effect performance.
To overcome these problems sun people has introduced BufferedReader and BufferedWriter classes.
That’s all about the FileReader Class in java. If you have any queries or feedback, please write us email at contact@waytoeasylearn.com. Enjoy learning, Enjoy Java.!!