Reading Text File Line by Line in Java 6 - Java
Home » Java

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
			}
		}
	}
}

 

More Related Posts in Java

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.