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

读取CSV到ArrayList触发ArrayIndexOutOfBoundsException问题求助

解决CSV加载时的ArrayIndexOutOfBoundsException异常

这个异常说明你访问数组索引0时,数组是空的(长度为0),大概率是CSV里存在空行或格式无效的行导致的,直接给你几个可行的解决办法:

  • 先过滤空行和无效行
    读取每行后先做校验,跳过空白行,同时检查拆分后的数组长度是否匹配ToyotaVehicle构造参数的数量:

    String line;
    while ((line = reader.readLine()) != null) {
        // 跳过空白行
        String trimmedLine = line.trim();
        if (trimmedLine.isEmpty()) {
            continue;
        }
        String[] parts = trimmedLine.split(",");
        // 假设构造ToyotaVehicle需要5个参数,就检查parts.length >=5,根据你的实际情况调整
        if (parts.length < 5) {
            System.err.println("跳过格式错误的行:" + line);
            continue;
        }
        // 实例化对象并加入集合
        ToyotaVehicle vehicle = new ToyotaVehicle(parts[0], parts[1], parts[2], parts[3], parts[4]);
        vehicleList.add(vehicle);
    }
    
  • 打印出错行定位问题
    在拆分前加一行打印代码,直接查看触发异常的行内容:

    String line = reader.readLine();
    while (line != null) {
        System.out.println("正在处理行:" + line); // 打印当前行,快速定位问题
        // 后续拆分、校验代码
        line = reader.readLine();
    }
    

    运行后就能看到是空行、无分隔符的无效行还是其他问题导致的数组为空。

  • 确认CSV分隔符是否正确
    检查你的CSV文件实际用的分隔符,如果是分号;、制表符\t这类非逗号符号,要把split(",")改成对应的分隔符,比如split(";")或split("\t")。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 08:50:04