How to read a file in java?

Java provides several mechanism to read from File.

The most useful package that is provided for this is the

This class contains the Class BufferedReader under package How to use Java Bufferedreader

Let us see what this class has in store for us.

This class reads the text from an Input stream (like file) by buffering characters that efficiently reads characters, arrays or lines.

In general, each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream.

It is therefore advisable to wrap a BufferedReader around any Reader whose read() operations may be costly, such as java FileReaders and InputStreamReaders.

A typical usage would involve passing the file path to the BufferedReader as follows:

The code will look like: (Assuming you have a text file in D drive)

objReader = new BufferedReader(new FileReader("D:\DukesDiary.txt"));

This basically loads your file in the objReader.

Now, you will need to iterate through the contents of the file and print it.

The while loop in the below code will read the file until it has reached the end of file i. e. there is no contents in the readline - objReader.readLine() that basically returns a string.

Hence, the loop will iterate until it’s not null.

Bufferedreader Example:

The below code shows the complete implementation.


public class ReadFileExample {

public static void main(String[] args) {
BufferedReader objReader = null;
		try {
		String strCurrentLine;

			objReader = new BufferedReader(new FileReader("D:\DukesDiary.txt"));

        while ((strCurrentLine = objReader.readLine()) != null) {


		} catch (IOException e) {


		} finally {

			try {
				if (objReader != null)
			} catch (IOException ex) {


The above code has some very important handlings especially in the finally block of the code.

This code will ensure that the memory management is done efficiently and the objReader.close() method is called that releases the memory.