• Home
  • Testing
  • SAP
  • Web
  • Must Learn!
  • Big Data
  • Live Projects
  • Blog

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 java.io.Reader.

This class contains the Class BufferedReader under package java.io.BufferedReader 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.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

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) {

				System.out.println(strCurrentLine);
			}

		} catch (IOException e) {

			e.printStackTrace();

		} finally {

			try {
				if (objReader != null)
					objReader.close();
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
	}
}

Note:

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.

 

YOU MIGHT LIKE: