Super CSV (Java) - reading files with spaces in column names

I work with Super CSV and it looks like a terrific package.

My only concern is how to work with columns with spaces in their names. No, I can’t go back and rent space. These files will be transferred to me in 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 right.

How can I work with columns with spaces in the header (ie "Name", not "FirstName" or "firstName")?

Thank!

For coding examples, see here: http://supercsv.sourceforge.net/codeExamples_general.html

+3
source share
4 answers

You notice this line in the samples you are referencing:

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

That should give you column names, no?

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

I think I understand your question now. The String [] argument passed to the function readaccepts the property names of the class you want to read. It is positional, so it does not need to be called as headings. So, for example, you can have String[] header = inFile.getCSVHeader(), but then have a mapping headerName->propertyName, so if your header fields were:

First Name, Last Name, Age

but your class was

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

go to the readnot method (String[]) {"First Name", "Last Name", "Age"}as your header, but go to the readarray (String[]) {"FirstName", "LastName", "Years"}.

+2
source

CSV , - , . "" "firstName" bean .

+2

I understand this is a pretty old post, but others may be looking for an alternative simple solution. This is what I did to ensure that I only have alphabetic names with no spaces:

  final String[] header = beanReader.getHeader(true);

  for(int i = 0; i <= header.length -1 ; i++ ) {
    header[i] = header[i].replaceAll("[^a-zA-Z0-9]+","");
  }
+1
source

For the header with spaces to separate the display array and the bean header.

private final String[] header = new String[] { "First Name", "Last Name"}; private final String[] dataMapping = new String[] { "firstName", "lastName"}; beanWriter = new CsvBeanWriter(new FileWriter(path), CsvPreference.EXCEL_PREFERENCE); beanWriter.writeHeader(header); beanWriter.write(yourPojo, dataMapping, processors);

+1
source

Source: https://habr.com/ru/post/1752273/


All Articles