Java逐行打印文件等待用户回车触发的代码故障修复咨询
Java逐行打印程序修复方案
问题根因
- 核心原因:你的
excerpt.txt文件内容不存在换行分隔,BufferedReader.readLine()方法默认读取到换行符才会返回,因此会将整段无换行内容当作单行一次性读入,按下回车后就会打印完整段。 - 额外逻辑缺陷:文件内容全部读取完成后,
while(true)死循环不会自动退出,需要用户输入非空内容才能终止程序,不符合交互预期。 - 小概率原因:未指定文件读取编码,不同系统默认编码不一致可能导致换行符识别异常,触发整段读取的问题。
需修改的逻辑点
- 先校验
excerpt.txt的内容格式,确保每段你想要分批输出的内容末尾都添加了换行符 - 补充文件读取完成后的自动退出逻辑,避免死循环
- 可选优化:指定文件读取字符集、主动关闭IO流避免资源泄漏
修正后的完整代码
import java.io.*; import java.util.*; public class NoteCopier { public static void main(String[] args) { System.out.println("Hello! I copy an excerpt to the screen line for line" + " just press enter when you want a new line!"); // 用try-with-resources语法自动关闭IO流,无需手动释放 try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("excerpt.txt"), "UTF-8")); Scanner scan = new Scanner(System.in)) { String line = reader.readLine(); while (line != null) { String scanString = scan.nextLine(); if (scanString.isEmpty()) { System.out.println(line); line = reader.readLine(); } else { // 用户输入非空内容直接退出 break; } } // 文件读完自动提示退出 System.out.println("摘录已全部输出,程序退出"); } catch (IOException e) { e.printStackTrace(); } } }
内容的提问来源于stack exchange,提问作者Willardino
相关产品推荐
相关产品推荐

