Reading Text File in Java 6

Many times as a Java programmer we have to do this, reading text file in Java. This falls under Java file i/o, along with other file operations. We have covered many other Java file i/o examples already. Here is code you will need in Java 6 to read a file on the machine. It uses BufferReader through FileReader.

Reading Text File in Java

What is the functionality that we are implementing in code below?


  • Open a file using a file reader
  • Buffer the contents of file
  • Print buffered i.e. read contents line by line, until we hit the end of file
  • Check end of fileĀ if the line is null.

Reading Text File in Java

While doing this operations one must note following important things.

  • Benefit of using BufferReader is in performance. BufferReader buffers contents of file up to the buffer size in one go. This reduces the number of times it hits the file to get contents. Subsequently improves performance. One can define the buffer size depending on program memory.
  • Close the BufferReader in finally block so that it is closed any case.
  • In BufferReader.close you can opt to ignore exception.
  • To check the end of file you can also use fileReader.hasNextLine() method provided by Java
  • We are doing almost negligible exception handling here. It is good to handle exception as per your program requirements.

public class FileLineByLine {

	public static void main(String[] args) {
		FileLineByLine fileLBL = new FileLineByLine();


	public void readFileLineByLine(){
		BufferedReader buffReader = null;
			buffReader = new BufferedReader (new FileReader("C:\SampleFile.txt"));
			String line = buffReader.readLine();
			while(line != null){
				line = buffReader.readLine();
		}catch(IOException ioe){
			}catch(IOException ioe1){
				//Leave It


Java FileReader API Documentation

1 Trackback / Pingback

  1. :: Java – 6 – Read File :: | Mee To People

Leave a Reply

Your email address will not be published.