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

Java实现按回车键逐行显示文件内容if判断不生效问题

问题根本原因

  • 你调用的Scanner.next()方法默认会忽略所有前导空白分隔符(包括回车、空格、制表符),只有读取到非空白字符后遇到下一个分隔符才会停止返回结果。所以你只按回车的时候,next()方法会一直阻塞等待输入,根本不会返回空字符串,if (output.equals(""))的判断条件永远无法命中。
  • 额外隐藏问题:原代码没有处理文件读取结束后的边界情况,可能会出现输出null的问题,且重复创建了无必要的Scanner对象。

修复方案

把Scanner.next()替换为Scanner.nextLine()即可,nextLine()会读取从当前位置到行尾的所有内容,包括空行,你只按回车的时候返回的就是空字符串,刚好匹配你的判断条件。

修改后的可运行代码如下:

import java.util.Scanner;
import java.io.*;
public class LineByLine  {
   public static void main(String[] args) throws IOException {
    Scanner scanner = new Scanner(System.in);
    System.out.println("What is the filename?");
    String fileName = scanner.nextLine();
    BufferedReader buff = new BufferedReader(new FileReader(fileName));
    String line = buff.readLine();
    // 打印第一行内容
    System.out.println(line);
    while (line != null){
            // 用nextLine读取整行输入,按回车直接返回空字符串
            String enterInput = scanner.nextLine();
            if (enterInput.equals("")){
                line = buff.readLine();
                // 避免文件读取结束后打印null
                if (line != null) {
                    System.out.println(line);
                }
            }
    }
    // 手动关闭资源避免泄露
    buff.close();
    scanner.close();
   }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 00:06:03