I am trying to read a csv file using opencsv using HeaderColumnNameMappingStrategy. Opencsv populates my first column of csv as null everytime. Here is my code :
Entity Class :
@Entity
@Table(name = "MyEntity")
public class MyEntity {
@CsvBindByName(column = "status", required = true)
@Column(name = "status", length = 5, nullable = false)
private String status;
@CsvBindByName(column = "type", required = true)
@Column(name = "type", length = 5, nullable = false)
private String type;
@CsvBindByName(column = "percentage", required = true)
@Column(name = "percentage", nullable = false)
private Integer percentage;
@Column(name = "date", nullable = false)
@CsvBindByName(column = "date", required = true)
@CsvDate(value = "yyyy-MM-dd")
private Date date;
}
Reading logic:
final HeaderColumnNameMappingStrategy<MyEntity> mpngInfo= new HeaderColumnNameMappingStrategy<>();
mappingInfo.setType(MyEntity.class);
final CsvToBean<MyEntity> csvToBean = new CsvToBean<>();
File file = new File(<path>);
CSVReader reader = new CSVReader(new FileReader(file),';');
final List<MyEntity> list = csvToBean.parse(mpngInfo, reader, true);
//here in list the first column is always populated as null.
My CSV :
type;status;percentage;date ACTIVE;USD;25;2014-01-01 ACTIVE;GBP;25;2014-01-01
Note: Even if I switch 'type' with 'percentage' then it starts populating percentage as null because 'percentage' column becomes the first column.
I figured out the problem that is with the first character of file. In my case it's ""type;status;percentage;date
The problem is listed here : First character of the reading from the text file : 
How can I solve this in opencsv? Any Suggestions ?
I met the same problem.
I saved the csv file again by utf-8 without BOM.
Then the first column is set with correct value.
No code needs to be changed.
I use the text editor named sakura.After choosing encoding as utf-8,a checkbox of BOM is enabled.Uncheck it and save the csv file.I think other editors have the same BOM option.
A BOM-ed UTF-8 string will start with the three following bytes. EF BB BF
The three bytes added to your csv file may changed your first column name.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With