FileReader class is located in Java I/O package (java.io.FileReader). using this class we can read character files. In other words we can read character streams using FileRead class. If our purpose is reading bytes (raw bytes) from the files we can use FileInputStream.
Constructors of FileReader class.
FileReader(File file)
FileReader(String fileName)
FileReader(FileDescriptor fd) : File reader provides three handles to standard I/O streams such as in,out,err (FileDescriptor.in, FileDescriptor.out, FileDescriptor.err)
Lets see an example to undestand the FileReader class.
Related Articles
//© http://imagocomputing.blogspot.com/Output :
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
public class ReadTxtFile {
public static void main(String args[]) {
try{
FileReader fin=new FileReader("myFile.txt");
String fileContent="";
char buff[]=new char[512];
int len;
while((len=fin.read(buff))!=-1){
fileContent+=(new String(buff,0,len));
}
/*now fileContent variable contains
*the whole text in the targeted file
*/
System.out.println(fileContent);
fin.close();
}catch(FileNotFoundException e){
System.err.println("File not found : " + e.getMessage());
}catch(IOException e){
System.err.println("Error in file stream! : " + e.getMessage());
}
}
}
Explanation :
In line 9 we create FileReader object called fin
Then we read file iteratively. First we read set of characters into char array then we append it to fileContent variable.
After reading whole content we can do several manipulations with the file content in this example I have printed the file content to the standard output stream.
Class : FileReader
Since : JDK1.1