Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

csv

supercsv

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

like image 477
Justian Meyer Avatar asked Jun 29 '10 13:06

Justian Meyer


People also ask

How do I read a specific column in a CSV file in Java 8?

csv"; //create BufferedReader to read csv file BufferedReader br = new BufferedReader( new FileReader(strFile)); String strLine = ""; StringTokenizer st = null; int lineNumber = 0, tokenNumber = 0; //read comma separated file line by line while( (strLine = br. readLine()) !=

Do all lines in a CSV files have the same number of columns?

A CSV file should have the same number of columns in each row. A CSV file stores data in rows and the values in each row is separated with a separator, also known as a delimiter.

How do I add a header to an existing csv file in Java?

The file is created and the headers are inserted, but all the headers in same cell. csvFile. createNewFile(); CSVWriter csvWrite = new CSVWriter(new FileWriter(csvFile)); String heading = "eid,name,vid,emp_id,balance_amt,handover_to,entry_date \n"; csvWrite. writeNext(new String[]{heading});


1 Answers

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.

like image 173
maxwellb Avatar answered Sep 28 '22 15:09

maxwellb