Java中用BufferedReader配合try-with-resources读取文件,核心是让JVM自动关闭流以避免资源泄漏;必须在try括号内声明并初始化BufferedReader(需final或effectively final),它会在try块结束时自动调用close(),无需finally;推荐JDK11+使用Files.newBufferedReader或Files.readString,内置UTF-8编码与自动资源管理。

Java 中用 BufferedReader 配合 try-with-resources 读取文件,核心是让 JVM 自动关闭流,避免资源泄漏。只要把 BufferedReader 的创建写在 try 括号里,它就会在 try 块结束时自动调用 close(),不用手动写 finally。
基本写法:一行创建 + 逐行读取
最常用场景是按行读取文本文件,例如:
try (BufferedReader reader = new BufferedReader(new FileReader("data.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
这里 FileReader 本身不支持指定字符编码,默认用平台编码(可能出乱码),生产环境建议换成 InputStreamReader 包装 FileInputStream 并显式指定 UTF-8:
new BufferedReader(new InputStreamReader(new FileInputStream("data.txt"), StandardCharsets.UTF_8))- JDK 11+ 可直接用
Files.newBufferedReader(Paths.get("data.txt"), StandardCharsets.UTF_8),更简洁安全
读取全部内容(JDK 11+ 推荐)
如果只是想把整个文件转成字符串,JDK 11 提供了更简单的方式,底层仍用 BufferedReader,但封装好了:
立即学习“Java免费学习笔记(深入)”;
try {
String content = Files.readString(Paths.get("data.txt"), StandardCharsets.UTF_8);
System.out.println(content);
} catch (IOException e) {
e.printStackTrace();
}
这个方法内部自动使用 try-with-resources,无需关心流的生命周期,也默认用 UTF-8,适合小到中等大小文本文件。
注意事项和常见坑
-
BufferedReader必须是 final 或 effectively final 才能用于 try-with-resources,否则编译报错 - try-with-resources 会按声明顺序的逆序关闭资源(后声明的先关闭),多个资源用分号隔开即可
-
readLine()返回null表示到达文件末尾,不是错误,不要把它当成异常处理 - 如果文件不存在或无读取权限,抛出
IOException(或其子类如FileNotFoundException),需捕获或声明抛出
完整可运行示例(含异常处理)
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
public class ReadFileExample {
public static void main(String[] args) {
String filePath = "example.txt";
// 方式一:传统 BufferedReader + try-with-resources
try (BufferedReader reader = Files.newBufferedReader(Paths.get(filePath), StandardCharsets.UTF_8)) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.err.println("读取文件失败:" + e.getMessage());
}
// 方式二:JDK 11+ 简化版
try {
String content = Files.readString(Paths.get(filePath), StandardCharsets.UTF_8);
System.out.println("全部内容:" + content);
} catch (IOException e) {
System.err.println("读取文件失败:" + e.getMessage());
}
}
}
两种方式都确保资源被正确释放,推荐优先用 Files.newBufferedReader 或 Files.readString,语义清晰、编码安全、代码量少。


















