【问题标题】:Array Out of Bounds error while Reading 2 Column Csv File using OpenCsv使用 OpenCsv 读取 2 列 Csv 文件时出现数组越界错误
【发布时间】:2021-07-09 06:34:11
【问题描述】:

我正在使用 opencsv 库读取 2 列 CSV,我想将这 2 列作为键值对放在地图中。但是,只要 CSV 中有空行,我就会得到 Array Index out of bounds 异常。有什么办法可以避免吗?这是我的代码:

    Map<String, String> map = new HashMap<>();
    CSVReader csvReader;
    try (FileReader filereader = new FileReader(path)) {
        csvReader = new CSVReader(filereader);
        String[] nextRecord;
        while ((nextRecord = csvReader.readNext()) != null) {
            if (nextRecord[0] != null && nextRecord[1] != null) {
                map.put(nextRecord[0], nextRecord[1]);
            }
        }

    } catch (Exception e) {
        System.out.print(e);
    }

【问题讨论】:

  • 您文件中的所有条目都没有逗号。如果没问题,请粘贴您的文件内容。访问nextRecord[index]之前检查nextRecord数组的长度
  • 你可以通过检查行是否为空来避免它
  • 尝试使用readNextSilently并检查nextRecord != null &amp;&amp; nextRecord.length &gt; 1
  • 是的,检查长度解决了这个问题。谢谢大家

标签: java csv opencsv


【解决方案1】:

nextRecord 的数组可能为空,因此您需要在索引之前检查长度

改变

if(nextRecord[0]!=null && nextRecord[1]!=null){
     map.put(nextRecrod[0],nextRecord[1]);
}

if(nextRecord.length ==2 && nextRecord[0]!=null && nextRecord[1]!=null){
     map.put(nextRecrod[0],nextRecord[1]);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-19
    • 1970-01-01
    • 2022-11-12
    • 1970-01-01
    • 2013-03-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多