Search code examples
javaopencsv

Read csv file with Java OpenCSV


I have the following .csv file:

Company ABC                             
"Jan 1, 2020 - Sep 30, 2020"                                
Product Country Avg. monthly clients    Avg. month charge   Parts change    Impact  In stock    Clients in list City
Nissan Maxima   USA 6600    0%  -18%    Low 18      
BMW X7 M50i USA 18100   22% 0%  Low 28      
Volvo XC90  USA 880 0%  -12%    Low 10      
Opel Insignia   USA 320 -34%    -34%    Low 23      
Renult Triber   USA 140 -18%    -36%    Low 8       
Toyota Yaris    USA 880 0%  -28%    Low 30      
Ford Mondeo USA 70  -20%    -71%    Low 1       

for delimiter I have empty space(Tab). I tried to use this code in order to read the file using Opencsv:

@Getter
@Setter
public class CsvLine {

    @CsvBindByPosition(position = 1)
    private String model;

    @CsvBindByPosition(position = 2)
    private String country;
}

            String fileName = "C:\\in_progress\\zzz.csv";

            List<CsvLine> beans = new CsvToBeanBuilder(new FileReader(fileName))
                    .withType(CsvLine.class)
                    .withSeparator(' ')
                    .withSkipLines(1)
                    .build()
                    .parse();

            for(CsvLine item: beans){
                System.out.println(item.getModel());
            }

But I get this output:

 X C 9 0 
null
 I n s i g n i a     U S A   3 2 0   - 3 4 %     - 3 4 %     L o w   2 3         
null
 T r i b e r 
null
 Y a r i s   U S A   8 8 0   0 %     - 2 8 %     L o w   3 0         
null
 M o n d e o     U S A   7 0     - 2 0 %     - 7 1 %     L o w   1       
null
null

Do you know how I can the file properly with Java preferably with OpenCSV?

Test file https://www.dropbox.com/s/7jo4i3bs6h8at25/zzz.csv?dl=0


Solution

  • If your CSV file really uses the Tab character as field delimitier, it should be sufficient to change to:

                List<CsvLine> beans = new CsvToBeanBuilder(new FileReader(fileName))
                        .withType(CsvLine.class)
                        .withSeparator('\t')
                        .withSkipLines(2)
                        .build()
                        .parse();
    

    I changed withSeparator argument and increased the number of lines to skip to 2