7

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 ?

Community
  • 1
  • 1
New Bee
  • 1,007
  • 4
  • 18
  • 34

2 Answers2

27

I met the same problem.

Solution

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.

Reason

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.

Ender
  • 271
  • 3
  • 4
2

In intellij you can simply click on the file and on the top menu File -> File Properties -> Remove BOM. Which will do the magic for you :)

Marko
  • 101
  • 6