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

Java:修改代码实现从指定起始行到目标行读取文本文件

问题分析与修复方案

原代码的核心问题是没有跳过起始行之前的内容,直接将传入的from作为循环执行次数的计数器,导致调用display(3,5)时,只读取了前3行,而非第3到5行。

修复后的代码

public void display(int from, int to) throws FileNotFoundException {
    File f = new File(fileName);
    // 先处理文件不存在的情况,提前返回
    if (!f.exists()) {
        System.out.print("This File Does Not Exist");
        return;
    }

    Scanner sc = new Scanner(f);
    int currentLine = 1;

    // 先跳过起始行之前的所有行
    while (sc.hasNextLine() && currentLine < from) {
        sc.nextLine();
        currentLine++;
    }

    // 读取从from到to的目标行
    while (sc.hasNextLine() && currentLine <= to) {
        System.out.println(sc.nextLine());
        currentLine++;
    }

    sc.close();
}

关键修改点

  1. 新增行号追踪变量:用currentLine记录当前读取的行号,初始值为1(对应文件第一行)
  2. 跳过前置行:第一个循环专门跳过from行之前的内容,比如传入from=3时,会跳过前2行
  3. 读取目标范围:第二个循环从from行开始,读取到to行或文件结束为止
  4. 提前处理异常情况:文件不存在时直接输出提示并返回,避免后续无效操作

可选优化:参数合法性校验

如果需要处理非法输入(比如from小于1、to小于from),可以在代码开头添加校验:

// 参数合法性校验
if (from < 1 || to < from) {
    System.out.println("Invalid line range: from must be >= 1 and to >= from");
    return;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 06:45:30