编写csv文件时出现NullPointerException

时间:2014-11-06 07:23:59

标签: java nullpointerexception opencsv

我想用opencsv库写一个csv,但是,在运行代码时,我得到NullPointerException

public void exportToCSV(ArrayList<Data> list) throws IOException {
        log.info("write CSV file");

        String writerPath = "C:\\Users\\User\\Desktop\\Output\\output.csv";

        CSVWriter writer = new CSVWriter(new FileWriter(writerPath), ';');

        //headers
                String [] entries = {"ID", "Date"};

        writer.writeNext(entries);

        List<String[]> data = new ArrayList<String[]>();
        for (int m = 0; m < list.size(); m++) {
            data.add(new String[] {
                    list.get(m).getID,
                    (list.get(m).getDate().toString()==null) ? "null" : list.get(m).getDate().toString(), //Here i get the NullPointerException
            });
        }
        writer.writeAll(data);
        writer.close();
    }

我猜getDate()为空,哪个类型为Timestamp。但是,当StringgetDate()时,为什么我提出的解决方案无法编写null

我赞美你的回复!

1 个答案:

答案 0 :(得分:1)

list.get(m).getDate().toString()==null应更改为list.get(m).getDate()==null

如果list.get(m).getDate()null。在其上调用方法将导致NullPointerException