【发布时间】: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 && nextRecord.length > 1 -
是的,检查长度解决了这个问题。谢谢大家