Reading Text File Line by Line in Java 6
23 November 2009
No Comment
Here is code you will need in Java 6 to read a file on the machine. It uses BufferReader through FileReader. Some of the things you should remember are -
- Close the BufferReader in finally block so that it is closed any case.
- In BufferReader.close you can opt to ignore exception.
- Check the size of file you are reading as buffer.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class FileLineByLine {
public static void main(String[] args) {
FileLineByLine fileLBL = new FileLineByLine();
fileLBL.readFileLineByLine();
}
public void readFileLineByLine(){
BufferedReader buffReader = null;
try{
buffReader = new BufferedReader (new FileReader("C:\\SampleFile.txt"));
String line = buffReader.readLine();
while(line != null){
System.out.println(line);
line = buffReader.readLine();
}
}catch(IOException ioe){
ioe.printStackTrace();
}finally{
try{
buffReader.close();
}catch(IOException ioe1){
//Leave It
}
}
}
}









Leave your response!