![](/img/trans.png)
[英]Null Pointer Exception when trying to use (java.util.Random) in method - beginner Java
[英]FileParser Util java method showing null pointer exception
我正在编写一种用于解析csv文件的实用程序方法。 由于某种原因,此方法在插入地图列表期间显示了空指针异常。 我不知道为什么。 有人可以看着您并解释为什么会发生这种情况吗? 这是nullpointer异常的要点:
record.put(header[i].toString(), nextLine[i].toString());
这是要解析的文件:
id;state;city;total_pop;avg_temp
1;Florida;Miami;120000;76
2;Michigan;Detroit;330000;54
3;New Jersey;Newark;190000;34
和代码:
public class FileParserUtil {
public List<Map<String, String>> parseFile(String fileName, char seperator)
throws IOException {
CSVReader reader = new CSVReader(new FileReader(fileName), seperator);
Map<String, String> record = null;
List<Map<String, String>> rows = null;
// int colcnt = reader.readNext().length;
String[] header = reader.readNext();
String[] nextLine;
while ((nextLine = reader.readNext()) != null) {
for (int i = 0; i< nextLine.length; i++){
System.out.println(header[0]);
System.out.println(nextLine[0]);
System.out.println(header[1]);
System.out.println(nextLine[1]);
System.out.println(nextLine.length);
record.put(header[i].toString(), nextLine[i].toString());
}
rows.add(record);
}
reader.close();
return rows;
}
}
您的可变header[i]
可能没有nextLine[i]
长度相同,因此您不能使用相同的索引i
来检索其元素。
编辑:我想你忘了初始化Map<String, String> record
。 是吗
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.