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?

We

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

References:

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.


*