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.
//© http://imagocomputing.blogspot.com/ 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()); } } }Output :
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
2 comments:
Using String class and new String objects to concatenate text content is not that efficient.
Use a StringBuffer or StringBuilder instead.
Also char array to string conversion is not needed with them.
Also you could wrap the FileReader with a BufferedReader to simplify the code.
Thanks bro.
Obviously it is not efficient. But I wanted to show how to read a textfile using early Java classes.
I hope to post different ways to read textFiles in another posts.
Post a Comment