org.supercsv.exception.SuperCsvCellProcessorException:输入值应该是java.lang.String类型,但是java.util.Date

时间:2015-01-10 01:10:34

标签: java csv supercsv

我正在使用SuperCsv将csv文件解析为Javabeans,然后将其保存在数据库表中。尝试输入日期列时出现以下异常。在阅读了superscv API和documetation后,我真的无法理解如何正确地将csv写入Javabean并将其保存到数据库中。例外:

org.supercsv.exception.SuperCsvCellProcessorException: the input value should be of     type java.lang.String but is java.util.Date processor=org.supercsv.cellprocessor.ParseDate context={lineNo=2, rowNo=2, columnNo=3, rowSource=[moredata, 450, Thu Jan 01 00:09:00 PST 2015]}

csv文件:

someData,23,01/09/2015
moredata,450,01/09/2015
evenMoreData,500,01/09/2015

我正在解析CSV,如下所示:

private List<Timeseries> readCSVToBean() throws IOException {
    ICsvBeanReader beanReader = null;

    List<Timeseries> timeSeries = new ArrayList<Timeseries>();
    try {
        beanReader = new CsvBeanReader(new FileReader(pathName),
                CsvPreference.STANDARD_PREFERENCE);

        // the name mapping provide the basis for bean setters 
        final String[] nameMapping = new String[]{"varval", "actualNum", "daterec"};
        //just read the header, so that it don't get mapped to Timeseries object
        final String[] header = beanReader.getHeader(false);
        final CellProcessor[] processors = getProcessors();

        Timeseries timeEntity;

        while ((timeEntity = beanReader.read(Timeseries.class, nameMapping,
                processors)) != null) {
            timeSeries.add(timeEntity);
        }

    } finally {
        if (beanReader != null) {
            beanReader.close();
        }
    }
    return timeSeries;
}

private static CellProcessor[] getProcessors() {

    final CellProcessor[] processors = new CellProcessor[]{
        new NotNull(), // varval
        new ParseInt(), // actualNum
        //new FmtDate("dd/MM/yyyy") 
        new ParseDate("dd/mm/yyyy") // Daterec
    };
    return processors;
}

Timeseries bean是:

public class Timeseries implements Serializable {
    private static final long serialVersionUID = 1L;

    private Integer timid;
    private String varval;
    private Integer actualnum;
    private Date daterec;

    // ...
}

1 个答案:

答案 0 :(得分:3)

如超级CSV website所述,ParseDate用于阅读(String - &gt; Date),FmtDate用于撰写( Date - &gt; String)。

您需要一组处理器进行阅读,另一组需要写入。