使用 OpenCsv 读取 2 列 Csv 文件时出现数组越界错误
Array Out of Bounds error while Reading 2 Column Csv File using OpenCsv
我正在使用 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]);
}
我正在使用 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]);
}