在Java开发中,读取txt文件是一项基础且常见的操作,无论是处理配置文件、解析日志数据,还是导入外部数据,都离不开对txt文件的读取操作,本文将详细介绍Java包中读取txt文件的多种方法,涵盖基础用法、编码处理、异常管理、性能优化及实际应用场景,帮助开发者全面掌握这一技能。

基础读取方法:从字符流到缓冲流
Java提供了多种读取文件的方式,核心围绕字节流(InputStream)和字符流(Reader)展开,对于txt文件这类文本内容,通常优先使用字符流,因为它能直接处理字符编码,避免字节与字符转换的复杂性。
使用FileReader逐字符读取
FileReader是Java.io包中的基础字符流类,用于读取文件中的字符数据,其基本用法是通过创建FileReader对象,调用read()方法逐个字符读取,直到文件末尾(返回-1)。
FileReader fr = new FileReader("example.txt");
int ch;
while ((ch = fr.read()) != -1) {
System.out.print((char) ch);
}
fr.close();
但这种方式效率较低,因为每次read()调用都会进行I/O操作,适合读取小文件。
使用BufferedReader缓冲流提升效率
BufferedReader是对FileReader的包装,它内部维护一个缓冲区(默认8KB),减少直接I/O操作次数,大幅提升读取效率,特别适合逐行读取文件内容,其readLine()方法可以直接读取一行文本:
BufferedReader br = new BufferedReader(new FileReader("example.txt"));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
这是最常用的txt读取方式之一,兼顾了效率与易用性。
Java 7+的Files类简化操作
Java 7引入了java.nio.file包,其中的Files类提供了更简洁的文件操作API,通过Files.newBufferedReader()方法,可以直接返回BufferedReader对象,无需手动关闭资源(配合try-with-resources):
try (BufferedReader br = Files.newBufferedReader(Paths.get("example.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
这种方式代码更简洁,且通过try-with-resources自动关闭资源,避免内存泄漏。
处理文件编码:避免乱码的关键
txt文件的编码格式(如UTF-8、GBK、ISO-8859-1等)直接影响读取结果的正确性,若编码不匹配,可能出现乱码问题,Java中通过InputStreamReader指定编码解决:

InputStreamReader isr = new InputStreamReader(
new FileInputStream("example.txt"), "UTF-8"
);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
或使用Files.newBufferedReader的charset参数:
try (BufferedReader br = Files.newBufferedReader(
Paths.get("example.txt"), StandardCharsets.UTF_8
)) {
// 读取逻辑
}
注意:若不确定文件编码,可借助工具(如juniversalchardet)检测,或通过文本编辑器打开文件查看编码信息。
异常处理与资源管理:确保代码健壮性
文件操作可能抛出IOException(如文件不存在、权限不足、读取中断等),因此必须进行异常处理,文件流(如FileReader、BufferedReader)属于系统资源,若未正确关闭,会导致资源泄漏。
传统try-catch-finally处理
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("example.txt"));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.err.println("读取文件失败: " + e.getMessage());
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
推荐使用try-with-resources(Java 7+)
try-with-resources实现了AutoCloseable接口,能自动关闭资源,代码更简洁安全:
try (BufferedReader br = new BufferedReader(
new InputStreamReader(new FileInputStream("example.txt"), "UTF-8")
)) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.err.println("读取文件异常: " + e.getMessage());
}
关键点:所有在try()中声明的资源,都会在代码块执行完毕后自动关闭,即使发生异常也能保证资源释放。
性能优化与高级技巧:应对大文件与复杂场景
大文件读取:避免内存溢出
对于大文件(如GB级txt),使用BufferedReader逐行读取即可,因其流式处理不会一次性加载整个文件到内存,若需分块读取字节(如处理二进制混合文件),可使用InputStream的read(byte[] b)方法:
try (InputStream is = new FileInputStream("large.txt")) {
byte[] buffer = new byte[8192]; // 8KB缓冲区
int bytesRead;
while ((bytesRead = is.read(buffer)) != -1) {
// 处理读取的字节数据
String chunk = new String(buffer, 0, bytesRead, "UTF-8");
System.out.print(chunk);
}
}
NIO(New I/O)提升性能
Java NIO(java.nio.file)提供了非阻塞I/O和文件通道(FileChannel),适合高并发场景,使用Files.lines()返回Stream,支持流式处理:
try (Stream<String> lines = Files.lines(
Paths.get("example.txt"), StandardCharsets.UTF_8
)) {
lines.forEach(System.out::println); // 并行处理可用parallel()
}
Files.lines()返回的Stream是懒加载的,且底层使用缓冲区,性能优于传统BufferedReader。

处理特殊格式:CSV、JSON等
若txt文件为CSV格式,可逐行读取后用split(“,”)分割;JSON格式则需借助第三方库(如Gson、Jackson),例如读取CSV:
try (BufferedReader br = Files.newBufferedReader(Paths.get("data.csv"))) {
String line;
while ((line = br.readLine()) != null) {
String[] fields = line.split(","); // 简单分割,实际需考虑引号等复杂情况
System.out.println(Arrays.toString(fields));
}
}
实际应用场景:从配置文件到数据导入
读取配置文件
应用程序常将配置信息存储在txt文件中(如key=value格式),逐行读取后解析为Map:
Map<String, String> config = new HashMap<>();
try (BufferedReader br = Files.newBufferedReader(Paths.get("config.txt"))) {
String line;
while ((line = br.readLine()) != null) {
String[] kv = line.split("=", 2);
if (kv.length == 2) {
config.put(kv[0].trim(), kv[1].trim());
}
}
}
日志文件解析
服务器日志通常为txt格式,读取时需过滤特定关键词或按时间范围筛选:
try (BufferedReader br = Files.newBufferedReader(Paths.get("server.log"))) {
br.lines()
.filter(line -> line.contains("ERROR")) // 过滤ERROR日志
.forEach(System.out::println);
}
数据导入导出
将txt文件中的数据导入数据库,或导出数据为txt格式,例如读取用户信息并存储到List:
List<User> users = new ArrayList<>();
try (BufferedReader br = Files.newBufferedReader(Paths.get("users.txt"))) {
String line;
while ((line = br.readLine()) != null) {
String[] data = line.split(",");
User user = new User(data[0], data[1], Integer.parseInt(data[2]));
users.add(user);
}
}
Java读取txt文件的方法多样,从基础的FileReader到高效的BufferedReader,再到NIO的Files.lines(),开发者可根据场景选择合适的方式,核心要点包括:指定正确编码、妥善处理异常、确保资源释放、优化大文件读取,通过掌握这些技巧,既能解决日常开发中的文件读取需求,又能保证代码的健壮性与性能。


















