Java FileReader Class
The FileReader class inherits from the InputStreamReader class. This class reads data from a stream character by character. You can create the required object through the following constructors.
Creates a new FileReader given the File from which data is to be read.
FileReader(File file)
Creates a new FileReader given the FileDescriptor from which data is to be read.
FileReader(FileDescriptor fd)
Creates a new FileReader given the file name from which data is to be read.
FileReader(String fileName)
After successfully creating a FileReader object, you can use the methods in the following list to operate on files.
| No. | Description |
|---|---|
| 1 |
public int read() throws IOException Reads a single character and returns an int variable representing the character read. |
| 2 |
public int read(char [] c, int offset, int len) Reads characters into the c array and returns the number of characters read. |
Example
Example
import java.io.*;
public class FileRead {
public static void main(String args[]) throws IOException {
File file = new File("Hello1.txt");
//Create a file
file.createNewFile();
// creates a FileWriter Object
FileWriter writer = new FileWriter(file);
//Write content to the file
writer.write("This\n is\n an\n example\n");
writer.flush();
writer.close();
//Create a FileReader object
FileReader fr = new FileReader(file);
char[] a = new char[50];
fr.read(a); //Read the contents in the array
for (char c : a)
System.out.print(c); //Print characters one by one
fr.close();
}
}
The compilation and execution result of the above example is as follows:
This is an example
Other Extensions
Java Stream