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

基于索引从日志文件打印指定行区间的Java开发需求及代码修正

修正后的Display.java代码及问题说明

现有代码的核心问题

  • 类名应为Display,需对应文件名Display.java
  • 文件读取操作未放在try块内,FileNotFoundException无法被正确捕获
  • 仅读取文件第一行就进入循环,未持续读取后续行,导致无限循环
  • 行范围判断逻辑错误:误用codePointAt()获取字符编码而非行索引,且存在语法缺失
  • 未自动管理IO资源,存在资源泄漏风险
  • 捕获文件不存在异常后未退出程序,不符合任务要求
  • 未处理用户输入格式错误、索引越界等异常情况

符合要求的修正代码

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Display {
    public static void main(String[] args) {
        // 定义文件路径,可根据实际情况调整
        String filePath = "logfile.txt";
        List<String> allLines = new ArrayList<>();

        // 读取文件内容到列表,同时处理文件不存在的情况
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                allLines.add(line);
            }
        } catch (FileNotFoundException e) {
            System.out.println("Cannot find logfile!");
            System.out.println("Exiting...");
            System.exit(0); // 退出程序
        } catch (IOException e) {
            System.err.println("Error reading file: " + e.getMessage());
            System.exit(1);
        }

        // 获取用户输入的起始和结束索引
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter start and end index separated by space:");
        int startIndex = -1;
        int endIndex = -1;

        try {
            startIndex = scanner.nextInt();
            endIndex = scanner.nextInt();
        } catch (Exception e) {
            System.err.println("Invalid input! Please enter two integers.");
            scanner.close();
            System.exit(1);
        }
        scanner.close();

        // 验证索引合法性
        if (startIndex < 0 || endIndex >= allLines.size() || startIndex > endIndex) {
            System.err.println("Invalid index range!");
            System.err.println("Valid range: 0 to " + (allLines.size() - 1));
            System.exit(1);
        }

        // 打印指定区间的行(包含首尾)
        System.out.println("Lines in range [" + startIndex + ", " + endIndex + "]:");
        for (int i = startIndex; i <= endIndex; i++) {
            System.out.println(allLines.get(i));
        }

        System.out.println("Exiting...");
    }
}

代码关键说明

  1. 类名与文件名:类名改为Display,对应任务要求的Display.java文件
  2. 文件读取与异常处理:使用try-with-resources自动管理BufferedReader,文件不存在时捕获FileNotFoundException,打印指定信息后调用System.exit(0)退出程序
  3. 行存储与索引处理:将文件所有行存入List,方便根据索引快速定位;验证用户输入的索引范围,避免越界
  4. 用户输入处理:捕获输入格式错误,给出明确提示后退出
  5. 任务要求匹配:完全实现文件不存在的提示退出,以及指定索引区间行的打印功能

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 13:50:46