Search code examples
javacsvsupercsv

Super CSV (Java) - Read Files with Spaces in Column Names


I'm working with Super CSV and it looks like an amazing package.

My only worry is how to work with columns with spaces in their names. No, I cannot go back and remove the spaces myself. These files will be given to me by the hundreds and I don't have time to go back and fix all 60 columns for each file and I can't trust everyone else to do it properly.

How can I work with columns with spaces in the title (i.e. "First Name" not "FirstName" or "firstName")?

Thanks!

For coding samples, look here: http://supercsv.sourceforge.net/codeExamples_general.html


Solution

  • You notice this line in the samples you link to:

    final String[] header = inFile.getCSVHeader(true);
    

    This should give you your column names, no?

    http://supercsv.sourceforge.net/javadoc/index.html

    I think I understand your question now. The String[] argument passed to the read function takes the property names of the class you want to read into. It is positional, so it doesn't have to be named anything like the headers. So, for example, you can have String[] header = inFile.getCSVHeader(), but then have a mapping of headerName->propertyName, so, if your header fields were:

    First Name, Last Name, Age
    

    but your class was

    getFirstName(), setFirstName(...);
    getLastName(), setLastName(...);
    getYears(), setYears();
    

    pass to the read method not (String[]) {"First Name", "Last Name", "Age"}, as your header is, but pass to read, a (String[]) {"FirstName", "LastName", "Years"} array.