0

我正在编写一种用于解析 csv 文件的实用程序方法。出于某种原因,此方法在插入映射列表期间显示空指针异常。我不确定为什么。有人可以看看这个并解释为什么会发生这种情况吗?这是空指针异常的要点:

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;

    }
}
4

1 回答 1

0

您的变量header[i]可能没有相同的长度nextLine[i],因此您不能使用相同的索引i来检索其元素。

编辑: 我想你忘了初始化Map<String, String> record. 是这样吗?

于 2013-10-09T00:39:47.660 回答