I'm using Univocity parser to parse CSV files and populating them in a Bean
.
The problem I'm facing is that I have two different files. Both the files are same in structure but they vary in the number of columns. They both refer the same Bean class.
For example:
File A contains(without header):
I|123|Hello
U|345|Hi
File B contains(without header):
123|Hello
345|Hi
The Bean Class definition is:
public class Bean {
@Trim
@Parsed(index = 0)
protected String action;
@Trim
@Parsed(index = 1)
protected Long id;
@Trim
@Parsed(index = 2)
protected String name;
......................
}
If I use the same bean for both files, it is expecting the same number of columns in both the files and it is failing.
Another approach which I think I can use is to have two different beans for different set of files, but I'm looking if there is any functionality in Univocity parser to handle this case.
Please help. Thanks.
You can set the headers "by hand" before parsing each input. For example:
CsvParserSettings s = new CsvParserSettings();
s.setHeaderExtractionEnabled(false);
CsvRoutines r = new CsvRoutines(s);
//set headers of input with 3 columns
s.setHeaders("action" , "id", "name");
for(Bean b : r.iterate(Bean.class, new StringReader("I,123,Hello\nU,345,Hi"))){
System.out.println(b);
}
//set headers of input with 2 columns
s.setHeaders("id", "name");
for(Bean b : r.iterate(Bean.class, new StringReader("123,Hello\n345,Hi"))){
System.out.println(b);
}
The above will work if you change your bean to use header names instead of column positions:
public class Bean {
@Trim
@Parsed
protected String action;
@Trim
@Parsed
protected Long id;
@Trim
@Parsed
protected String name;
I got the following output (after adding a toString()
method to the Bean
class):
Bean{action='I', id=123, name='Hello'}
Bean{action='U', id=345, name='Hi'}
Bean{action='null', id=123, name='Hello'}
Bean{action='null', id=345, name='Hi'}
Hope this helps!