Wednesday, May 9, 2012

How to read file in Java using BufferedReadetr with example

Example to demonstrate how to read a file in Java using BufferedReader classes with example. THis is most simple way to read file in java.
In this example readLine() method is used to read each line from file.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadFileExample1 
{
 public static void main(String[] args)
 {
  BufferedReader br = null;
  try 
  {
   String thisLise;
   br = new BufferedReader(new FileReader("D:\\db\\fileTest\\file1.txt"));
   while ((thisLise = br.readLine()) != null) 
   {
    System.out.println(thisLise);
   }
  } 
  catch (IOException e)
  {
   e.printStackTrace();
  }
  finally //finally closing the objects
  {
   try
   {
    if (br != null)br.close();
   } 
   catch (IOException ex)
   {
    ex.printStackTrace();
   }
  }
 }
}

No comments:

Post a Comment