Tuesday 21 February 2012

read file line by line

test.properties
#userInfo
#Tue Feb 21 19:58:00 IST 2012
age=26
name=usr
city=bangalore


package com.usr.io;

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

public class ReadFileLineByLine {
       public static void main(String[] args) {
              try{
                     File fin=new File("test.properties");
                     FileReader fr=new FileReader(fin);
                     BufferedReader br=new BufferedReader(fr);

                     StringBuilder sb=new StringBuilder();
                     String line="";

                     while((line=br.readLine())!=null){
                           sb.append(line);
                           sb.append("\n");

                     }
                      br.close();
                     System.out.println("File contents are:");
                     System.out.println(sb);

              }
              catch(FileNotFoundException ex){
                     ex.printStackTrace();
              }
              catch(IOException ex){
                     ex.printStackTrace();
              }
       }
}

output 
File contents are:
#userInfo
#Tue Feb 21 19:58:00 IST 2012
age=26
name=usr
city=bangalore