Search code examples
javacsvopencsv

Reading semicolon delimited csv


I have the below block of code which uses OpenCSV to read a CSV file and store the 7th column. The problem I face is that I use ; as delimiter in the CSV file but it takes , as delimiter as well. How can I avoid this?

Putting "" in CSV is not possible, since we get a non-editable file from client.

        CSVReader reader = null;
    String[] nextCsvLine = new String[50];
    String splitBy = ";";

    int count = 0;

    try {
        StringReader sr = new StringReader(new String(in, offset, len));
        reader = new CSVReader(sr);

        while ((nextCsvLine = reader.readNext()) != null) {
            for (String linewithsemicolon : nextCsvLine) {
                log.debug("Line read : "+linewithsemicolon);
                String[] b = linewithsemicolon.split(splitBy);
                if (count==0){
                    count++;
                    continue;
                }
                else    {      
                    detailItems.add(b[7]);
                    log.debug("7th position: "+b[7]);
                    count++;
                }                   
            }

Solution

  • Use the overloaded version with separator of OpenCSV

    CSVReader(reader, ';')
    

    Update (thanks to @Matt) - better use:

    CSVReaderBuilder(reader)
        .withCSVParser(new CSVParserBuilder()
            .withSeparator(';')
            .build()
        ).build()
    

    I think the counting was done a bit wrong:

    try (CSVReader reader = new CSVReader(sr, ';')) {
        String[] nextCsvLine;
        while ((nextCsvLine = reader.readNext()) != null) {
            int count = 0;
            for (String field: nextCsvLine) {
                log.debug("Line read : "+linewithsemicolon);
                if (count == 6) { // 7th column
                    detailItems.add(field);
                    log.debug("7th position: " + field);
                }                   
                count++;
            }
        }
    

    Instead the for-loop you could have done:

             if (nextCsvLine.length > 6) {
                 detailItems.add(nextCsvLine[6]);
             }
    

    Where the seventh field should have index 6.