How to read file in Java using BufferedReader ?

Hello,

Many times came we across a situation when we need to read file in Java using Java IO Operations.

We are going to read text file using BufferedReader. There are couple of way we can do it.


Here is hello.text file that we want to read using Java.

Hello
infybuzz
java


1. Using Java 8 (Files.newBufferedReader)


package com.infybuzz.file;

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class FileReaderDemo1 {

 public static void main(String[] args) {
  
  try (BufferedReader br = Files.newBufferedReader(Paths.get("D:\\hello.txt"))){
   
   String str = "";
   StringBuilder stringBuilder = new StringBuilder();
   
   //reading file line by line
   
   while((str = br.readLine()) != null){
    stringBuilder.append(str).append("\n");
   }
   
   System.out.println(stringBuilder.toString());
   
  }catch (IOException ex) {
   ex.printStackTrace();
  }
 }

}


Output

Hello
infybuzz
java

2. Using Java 7 With Automatic Resource Management


package com.infybuzz.file;

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

public class FileReaderDemo2 {

 public static void main(String[] args) {
  
  try (FileReader reader = new FileReader("D:\\hello.txt");
    BufferedReader br = new BufferedReader(reader)){
   
   String str = "";
   StringBuilder stringBuilder = new StringBuilder();
   
   //reading file line by line
   
   while((str = br.readLine()) != null){
    stringBuilder.append(str).append("\n");
   }
   
   System.out.println(stringBuilder.toString());
   
  }catch (IOException ex) {
   ex.printStackTrace();
  }
 }

}

Output

Hello
infybuzz
java

If you do not have idea about Automatic Resource management then just check out below post.
Automatic Resource Management in Java

3. If you are using Java version older than Java 7.


package com.infybuzz.file;

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

public class FileReaderDemo2 {

 public static void main(String[] args) {
  
  FileReader reader = null;
  
  BufferedReader br = null;
  
  try {
   
   reader = new FileReader("D:\\hello.txt");
   
   br = new BufferedReader(reader);
   
   String str = "";
   StringBuilder stringBuilder = new StringBuilder();
   
   //reading file line by line
   
   while((str = br.readLine()) != null){
    stringBuilder.append(str).append("\n");
   }
   
   System.out.println(stringBuilder.toString());
   
  }catch (IOException ex) {
   try {
    
    if(br != null) {
     br.close();
    }
    
    if(reader != null) {
     reader.close();
    }
    
   } catch(IOException e) {
    e.printStackTrace();
   }
   
   ex.printStackTrace();
  }
 }

}

Output

Hello
infybuzz
java