FileReader
class in Java is used to read character data from files. FileReader
class is available in the java.io
package.
What is FileReader ?
The FileReader
class in Java is designed to read character data from files sequentially. FileReader
class extends InputStreamReader
. FileReder class provide a simple option to access files as a stream of characters.
FileReader Constructors
FileReader fileReader = new FileReader(String fileName);
FileReader fileReader = new FileReader(File f);
FileReader Methods
int read()
public int read()
throws java.io.IOException
This method reads a single character from the file and returns the equivalent UNICODE value of the character. If there is no next character available then this method returns -1. This method returns the UNICODE value (int). At the time of printing the character, we have to perform typecasting.
int read(char[] cbuf )
public int read( @NotNull char[] cbuf ) throws java.io.IOException
This method reads characters into an array. and returns the number of character reads.
void close()
public void close()
throws java.io.IOException
This method is used to close the FileReader and release any resource associated with it. This method should be called when the FileReader is no longer needed.
Using FileReader
package file;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class FileReaderExample {
public static void main(String[] args) throws IOException {
FileReader fileReader = new FileReader("java.txt");
int character;
while ((character=fileReader.read()) != -1){
System.out.println((char)character);
}
}
}
Note- By using FileReader class we can read data from the file character by character which is not convenient for the programer. To overcome this problem we can use BufferReader.
3 thoughts on “FileReader in Java”