Monday, May 31, 2010

Reading Text Files In a Java Program II :: Using a FileReader and a BufferedReader


In this example we use a FileReader object wrapped by a BufferedReader object to read a plain text file. This method is more efficient than reading raw bytes and converting them into character array.

Constructors of BufferedReader class
BufferedReader(Reader in)
BufferedReader(Reader in, int inpBuffSize) : When we use this constructor we must specify the size of the input buffer.

Code:
//© http://imagocomputing.blogspot.com/ 
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;

public class ReadTxtFile{
 public static void main(String args[]){
  try{
   String fileContent="";
   //create a FileReader object(fin)
   FileReader fin=new FileReader("myFile2.txt");
   //wrap FileReader object(fin) using a BufferedReader 
   BufferedReader buffR=new BufferedReader(fin);
   String line;
   while((line=buffR.readLine())!=null){
    fileContent+=line+"\n";
   }
   System.out.println(fileContent);
   buffR.close();
   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:
Line 12 : We create a FileReader object to read out targeted text file
Line  14: Wrap the FileReader object (fin) by a BufferedReader(buffR) this allows us to read file content line by line.

Class FileReader Since : JDK1.1
Class BufferedReader Since : JDK1.1

0 comments:

Post a Comment

Stats

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

lankeeya sithuwili

Blog Catalogs

 

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