使用OpenCsv读取2列Csv文件时发生数组越界错误



我正在使用opencsv库读取一个2列CSV,我想将这2列作为键值对放在映射中。然而,每当CSV中有空行时,我就会得到数组索引越界异常。有什么办法可以避免这种情况吗?这是我的代码:

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

数组可能为空,因此在对其进行索引之前需要检查长度

更改

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]);
}

最新更新