Sunday, May 30, 2010

Reading Text Files In a Java Program :: Using a FileReader


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.
//© 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:

Anonymous said...

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.

Kanishka Dilshan on May 30, 2010 at 11:40 PM said...

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

Stats

ලාංකීය සිතුවිලි

lankeeya sithuwili

Blog Catalogs

 

Let's Learn Java API. Copyright 2010 All Rights Reserved