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

Java从文本文件加载数组时文件不存在的异常处理问题修复问询

问题根因

捕获FileNotFoundException异常后仅打印提示,未中断执行流程,仍返回初始化全为0的静态数组,导致后续打印等操作正常执行,输出无效的全0数组。

修复思路
  • 异常触发后终止后续无效流程:可以选择抛出运行时异常直接终止程序,或返回空标识供上层调用方判断是否继续执行
  • 优化不合理的静态数组设计,避免全局状态污染
  • 可选补充:优化数组读取逻辑,适配输入数据长度,避免数组越界异常
修复后完整代码
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;

// 类名修正为符合Java规范的大驼峰格式
public class ReadFile {
    private int[] array1;
    
    public int[] chooseFile() {
        try {
            Scanner s = new Scanner(new File("input.txt"));
            // 先统计文件中整数数量,避免数组越界
            int count = 0;
            while (s.hasNextInt()) {
                count++;
                s.nextInt();
            }
            s.close();
            
            // 重新读取内容存入数组
            array1 = new int[count];
            Scanner s2 = new Scanner(new File("input.txt"));
            int i = 0;
            while (s2.hasNextInt()) {
                array1[i++] = s2.nextInt();
            }
            s2.close();
            return array1;
        } catch (FileNotFoundException e) {
            System.err.println("The file does not exist!");
            // 抛出运行时异常终止程序,也可改为return null,在上层调用处判断非空再执行后续操作
            throw new RuntimeException("程序终止:输入文件不存在", e);
        }
    }
    
    public ReadFile() {
    }
    
    public ReadFile(int[] array1) {
        this.array1 = array1;
    }
    
    public void printArray() {
        System.out.println("Datas in the array");
        System.out.println(Arrays.toString(array1));
        System.out.println();
    }

    // 测试入口
    public static void main(String[] args) {
        ReadFile rf = new ReadFile();
        rf.chooseFile();
        rf.printArray();
    }
}
关键改动说明
  • 异常捕获块中新增运行时异常抛出逻辑,文件不存在时直接终止程序,不会执行后续打印操作;如果需要更灵活的处理,可把抛出异常改为return null,在调用chooseFile后判断返回值非空再调用printArray
  • 将原本的静态数组改为成员变量,避免全局静态状态被意外修改的问题
  • 新增数组长度动态计算逻辑,避免输入文件中整数数量超过5时触发数组越界异常
  • 修正类名、方法名符合Java命名规范,新增无参构造方法适配实例化需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 04:45:04