You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改Java代码读取含空行的文本文件并保留空行?

读取包含空行的文本文件并完整保存为字符串

问题分析

你提供的两种实现中,Implementation 2存在判断逻辑错误和内容覆盖问题;Implementation 1本身可以读取空行,但字符串拼接的方式性能较差。

修改后的实现方案

方案1:优化BufferedReader实现(保留空行+提升性能)

原循环逻辑可正确读取空行,改用StringBuilder避免频繁创建字符串对象,同时完整保留空行结构:

File templateFile = new File(templatePath);
StringBuilder oldContent = new StringBuilder();
BufferedReader reader = new BufferedReader(new FileReader(templateFile));

String line;
// readLine()遇空行返回""而非null,循环会继续执行
while ((line = reader.readLine()) != null) {
    oldContent.append(line).append(System.lineSeparator());
}
// 转换为最终字符串
String result = oldContent.toString();

// 关闭流(推荐用try-with-resources自动关闭)
reader.close();

说明:空行通过append(line)被保留,加上换行符后,最终结果与原文件的空行结构完全一致。

方案2:修复Scanner实现(正确识别空行)

原Scanner代码的问题:hasNext()默认跳过空白行,且每次赋值会覆盖之前的内容。修改后:

File templateFile = new File(templatePath);
StringBuilder oldContent = new StringBuilder();
Scanner sc = new Scanner(templateFile);

// 用hasNextLine()判断,确保空行也被识别
while (sc.hasNextLine()) {
    oldContent.append(sc.nextLine()).append(System.lineSeparator());
}
String result = oldContent.toString();

sc.close();

说明:hasNextLine()会检查所有行(包括空行),配合StringBuilder拼接,完整保留原文件的空行。

额外简洁方案(Java 8+)

使用Files类的方法可更高效实现:

import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

// ...
List<String> lines = Files.readAllLines(Paths.get(templatePath), StandardCharsets.UTF_8);
String result = String.join(System.lineSeparator(), lines);
// 若需保留文件末尾换行符,可追加:result += System.lineSeparator();

内容的提问来源于stack exchange,提问作者Tim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 07:01:08