How to read a file in Java with BufferedReader?

In this section, we will show you how to use java.io.BufferedReader to read content from a file.

1. Files.newBufferedReader (Java 8)

In Java 8, there is a new method Files.newBufferedReader(Paths.get("file")) to return a BufferedReader

myFile.txt


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

public class Main {

public static void main(String[] args) {

StringBuilder stringBuilder = new StringBuilder();

try (BufferedReader bufferedReader = Files.newBufferedReader
(Paths.get("C:\\Users\\91807\\Desktop\\myFile.txt"))) {

// read line by line
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}

} catch (IOException e) {
System.err.format("IOException: %s%n", e);
}

System.out.println(stringBuilder);

}

}

Console Output:
ABC
HIJ
KLM
NOP
QRS

2. BufferedReader

2.1 A classic BufferedReader with JDK 1.7 try-with-resources to auto close 

the resources.

Main.java

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

public class Main {

public static void main(String[] args) {

try (FileReader reader = new FileReader
("C:\\Users\\91807\\Desktop\\myFile.txt");
BufferedReader bufferedReader = new BufferedReader(reader)) {

// read line by line
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}

} catch (IOException e) {
System.err.format("IOException: %s%n", e);
}
}

}

2.2 In the old style, we have to close everything manually.

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

public class Main {

public static void main(String[] args) {

BufferedReader br = null;
FileReader fr = null;

try {

fr = new FileReader("C:\\Users\\91807\\Desktop\\myFile.txt");
br = new BufferedReader(fr);

// read line by line
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}

} catch (IOException e) {
System.err.format("IOException: %s%n", e);
} finally {
try {
if (br != null)
br.close();

if (fr != null)
fr.close();
} catch (IOException ex) {
System.err.format("IOException: %s%n", ex);
}
}

}

}

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Spring Boot + Mockito simple application with 100% code coverage

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete