javacsvsupercsv

Parsing Strings in SuperCSV


@Carlo V. Dango I have simplified my question and I have read the documentation--good advice not to panic. Still, I have problems. Help me solve one and it will solve them all. Thank you.

Question: When I have a csv record that is missing a non-String field, how (or even can I) convert the missing entry to a default value, or at least, not throw NullPointerException? Optional cellProcessor doesn't appear to prevent the error either.

This the program taken essentially from the SuperCSV website.

package com.test.csv;
import java.io.FileReader;

import org.supercsv.cellprocessor.ParseBigDecimal;
import org.supercsv.cellprocessor.ParseDate;
import org.supercsv.cellprocessor.ParseInt;
import org.supercsv.cellprocessor.ift.CellProcessor;
import org.supercsv.io.CsvBeanReader;
import org.supercsv.io.ICsvBeanReader;
import org.supercsv.prefs.CsvPreference;


public class CSVReader {

private static final CellProcessor[] cellProcessor = new CellProcessor[] {
    null,
    null,
    new ParseInt(),
    new ParseDate("yyyyMMdd"),      
    new ParseBigDecimal()       
};

public static void main (String[] args ) throws Exception {

    CsvPreference pref = new CsvPreference('"', '|', "\n");

    ICsvBeanReader inFile = new CsvBeanReader(new FileReader("C:\\temp\\sapfilePipe.txt"), pref);
    try {
        final String[] header = inFile.getCSVHeader(true);
        User user;
        while ((user = inFile.read(User.class, header, cellProcessor)) != null) {
            System.out.println(user);
        }
    } finally {
        inFile.close();
    }

}

}

here is the CSV file I'm reading. Notice in the first record there is a missing field (age).

firstName|lastName|age|hireDate|hourlyRate
A.|Smith|  |20110101|15.50

My User bean:

package com.test.csv;

import java.math.BigDecimal;
import java.util.Date;

public class User {

private String firstName;
private String lastName;
private int age;
private Date hireDate;
private BigDecimal hourlyRate;
    ...getters/setters...   

Here is the error:

Exception in thread "main" java.lang.NullPointerException
    at org.supercsv.io.CsvBeanReader.fillObject(Unknown Source)
    at org.supercsv.io.CsvBeanReader.read(Unknown Source)
    at com.glazers.csv.CSVReader.main(CSVReader.java:31)

Thanks.


Solution

  • The list reader reads each line into a list of strings. It seems this is what you are looking for.

    http://super-csv.github.io/super-csv/apidocs/org/supercsv/io/CsvListReader.html

    or as shown here http://super-csv.github.io/super-csv/examples_reading.html you can set the processor to null if you don't want anything specific done.