Java中推荐用Files.newBufferedReader配合try-with-resources按行读取文件,显式指定UTF_8编码避免乱码,并自动关闭资源;readLine()返回null表示文件结束,可结合trim()过滤空行或注释,小文件可存入List,大文件应边读边处理。

Java 中使用 BufferedReader 按行读取文件内容,核心是结合 FileReader(或更推荐的 InputStreamReader + Files.newInputStream)构造缓冲读取器,再用 readLine() 循环读取。关键要注意字符编码、资源关闭和异常处理。
基本写法:try-with-resources 自动关流
这是最推荐的方式,能确保流在使用后自动关闭,避免资源泄漏:
import java.io.*;
import java.nio.file.*;
public class ReadFileExample {
public static void main(String[] args) {
String filePath = "data.txt";
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());
}
}
}
-
Files.newBufferedReader内部已封装好InputStream和InputStreamReader,直接指定编码(如UTF_8),避免乱码 -
try-with-resources会自动调用close(),无需手动写finally块 -
readLine()返回null表示到达文件末尾,不包含换行符
兼容老版本 JDK:手动构造 FileReader(慎用编码)
如果用 FileReader,它默认使用平台编码(Windows 是 GBK,Linux/macOS 通常是 UTF-8),容易出乱码:
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();
}
- 仅适用于确定文件编码与系统默认编码一致的场景
- 生产环境强烈建议用
Files.newBufferedReader显式指定编码
读取时跳过空行或做简单过滤
可在循环中加判断,比如忽略空白行或注释行:
立即学习“Java免费学习笔记(深入)”;
while ((line = reader.readLine()) != null) {
line = line.trim();
if (!line.isEmpty() && !line.startsWith("#")) {
System.out.println(line);
}
}
-
trim()去首尾空格,再判断是否为空字符串 - 适合读取配置文件、CSV 前导说明等场景
把所有行读进 List 方便后续处理
如果需要随机访问或多次遍历,可以一次性加载到集合中:
List<String> lines = new ArrayList<>();
try (BufferedReader reader = Files.newBufferedReader(Paths.get("data.txt"), UTF_8)) {
String line;
while ((line = reader.readLine()) != null) {
lines.add(line);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
- 适合小到中等大小文件(几 MB 以内)
- 大文件慎用,避免内存溢出;此时应坚持边读边处理
不复杂但容易忽略编码和关流——用 Files.newBufferedReader + try-with-resources 就够了。


















