How to read file in Java – BufferedReader

1. Overview

In this example, we will use a BufferedReader class to read a file named "sample.txt". BufferedReader class is used to read the text from a character-based input stream. It can be used to read data line by line by readLine() method. It makes the performance fast.

2. Read File Using BufferedReader Examples

BufferedReader class offers few read methods to read a file by character by character or line by line. Let's write examples to read file character by character.
package com.javaguides.javaio.fileoperations.examples;

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

/**
 * This Java program demonstrates how to read file in Java – BufferedReader.
 * @author javaguides.net
 */

public class BufferedReaderExample {
 public static void main(String[] args) {
  try (FileReader fr = new FileReader("C:/workspace/java-io-guide/sample.txt"); 
    BufferedReader br = new BufferedReader(fr);) {
   int i;
   while ((i = br.read()) != -1) {
    System.out.print((char) i);
   }
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}
Let's write examples to read file line by line.
package com.javaguides.javaio.fileoperations.examples;

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

/**
 * This Java program demonstrates how to to read file line by line.
 * @author javaguides.net
 */

public class BufferedReaderExample {
 public static void main(String[] args) {
  try (FileReader fr = new FileReader("C:/workspace/java-io-guide/sample.txt");
    BufferedReader br = new BufferedReader(fr);) {
   String sCurrentLine;

   while ((sCurrentLine = br.readLine()) != null) {
    System.out.println(sCurrentLine);
   }
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}

3. Reference

Comments