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);
}
}

}

}

Comments

Popular posts from this blog

Spring Boot OpenAI Integration: Step-by-Step Guide

Orchestration-Based Saga Architecture and Spring Boot Microservices Implementation Guide

Spring Boot 3 + Angular 15 + Material - Full Stack CRUD Application Example