We can use FileReader to Read Character Data from the file.
Constructors :
FileReader fr = new FileReader(String fileName);
FileReader fr = new FileReader(File fileReference);
Note : If the file does not exist then, FileReader will throw java.io.FileNotFoundException
Methods :
int read(); //returns unicode value of character
int read(char[] ch); //returns number of characters copied from file to array
void close();
Example of : int read() method
package com.fileDemo;
import java.io.File;
import java.io.FileReader;
public class Demo {
public static void main(String[] args) throws Exception {
File f = new File("/home/tyson/Desktop/temp/file1"); //throws exception if file is not present
FileReader fr = new FileReader(f);
int x = fr.read();
while(x!=-1) {
System.out.print((char)x); //need to type cast to convert unicode to its character value
x = fr.read();
}
fr.close();
}
}
Example of : int read(char []) method
package com.fileDemo;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class Demo {
public static void main(String[] args) throws IOException {
File f = new File("/home/tyson/Desktop/temp/file1");
char[] ch = new char[(int)f.length()];
FileReader fr = new FileReader(f);
fr.read(ch);
for(char c : ch) {
System.out.print(c);
}
fr.close();
}
}
Note : Line by line reading is not possible in FileReader hence the concept of BufferedReader.