400. Java 文件操作基础 - 使用 Buffered Stream I/O 读取文本文件

0 阅读1分钟

400. Java 文件操作基础 - 使用 Buffered Stream I/O 读取文本文件

在 Java 中,Files.newBufferedReader(Path, Charset) 方法可以 高效地打开文件进行读取,返回一个 BufferedReader 对象。这个对象可以让你逐行读取文本文件,避免一次性读取整个文件带来的性能问题。


1️⃣ 逐行读取文本文件

BufferedReader 提供了 readLine() 方法,可以逐行读取文件内容。

示例代码(Java SE 7+):

import java.nio.file.*;
import java.io.BufferedReader;
import java.io.IOException;

public class LineCountExample {
    public static void main(String[] args) {
        Path path = Paths.get("file.txt");
        long count = 0L;

        try (BufferedReader reader = Files.newBufferedReader(path)) {
            String line = reader.readLine();
            while (line != null) {
                count++;
                line = reader.readLine();
            }
        } catch (IOException e) {
            System.err.println("读取文件异常: " + e.getMessage());
        }

        System.out.println("文件行数 = " + count);
    }
}

💡 注意点:

  • readLine() 返回的字符串 不包含换行符
  • 当到达文件末尾时,readLine() 返回 null
  • 使用 try-with-resources 自动关闭 BufferedReader,避免资源泄漏。

2️⃣ 使用 Java SE 8+Stream API

从 Java SE 8 开始,BufferedReader 提供了 lines() 方法,可以将文件的每一行转换成 Stream,方便使用 Stream API 进行处理,比如统计行数、过滤、映射等。

示例代码:

import java.nio.file.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.stream.Stream;

public class LineCountStreamExample {
    public static void main(String[] args) {
        Path path = Paths.get("file.txt");

        try (BufferedReader reader = Files.newBufferedReader(path);
             Stream<String> lines = reader.lines()) {

            long count = lines.count();
            System.out.println("文件行数 = " + count);
        } catch (IOException e) {
            System.err.println("读取文件异常: " + e.getMessage());
        }
    }
}

✅ 优点:

  • 代码更加简洁
  • 可以直接利用 Stream API 进行复杂处理
  • Stream 继承自 AutoCloseable,配合 try-with-resources 可以自动关闭流

3️⃣总结

  1. 演示逐行读取与 Stream 读取的区别

    • readLine() 适合简单逐行读取
    • lines() 适合复杂数据处理
  2. 展示 Stream 的处理能力

    • 例如统计包含特定关键字的行数:
    long keywordCount = reader.lines()
                              .filter(l -> l.contains("Java"))
                              .count();
    System.out.println("包含 'Java' 的行数 = " + keywordCount);
    
  3. 强调资源管理

    • try-with-resources 是最佳实践,保证文件和流被正确关闭