How to read file in Java: BufferedReader Example

How to read a file in Java?

Java provides several mechanisms 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

What is BufferedReader in Java?

BufferedReader is Java class to reads the text from an Input stream (like a file) by buffering characters that seamlessly 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:
objReader = new BufferedReader(new FileReader("D:\DukesDiary.txt"));
//Assuming you have a text file in D drive
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
while ((strCurrentLine = objReader.readLine()) != null) {
    System.out.println(strCurrentLine);
}
strCurrentLine reads the current line and objReader.readLine() returns a string. Hence, the loop will iterate until it’s not null.

BufferedReader Example:

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.

BufferedReader JDK7 Example:

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

public class ReadFileExample_jdk7 {

 private static final String FILENAME = "D:\\DukesDiary.txt";

 public static void main(String[] args) {

  try (BufferedReader br = new BufferedReader(new FileReader(FILENAME))) {

   String strCurrentLine;

   while ((strCurrentLine = br.readLine()) != null) {
    System.out.println(strCurrentLine);
   }

  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}

No comments:

Post a Comment