简体   繁体   中英

Apache commons CSV: quoted input doesn't work

import java.io.IOException;
import java.io.StringReader;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;

I try to parse a simple csv file with Apache CSV parser. It works fine as long as I don't use quotes. When I try to add a quote to the input

"a";42

it gives me the error:

invalid char between encapsulated token and delimiter

Here is a simple, complete code:

public class Test {

    public static void main(String[] args) throws IOException {
        String DATA = "\"a\";12";
        CSVParser csvParser =    
        CSVFormat.EXCEL
            .withIgnoreEmptyLines()
            .withIgnoreHeaderCase()
            .withRecordSeparator('\n').withQuote('"')
            .withEscape('\\').withRecordSeparator(';').withTrim()
            .parse(new StringReader(DATA));
    }

}

I simply can't find out what I've missed in the code.

The problem was so trivial I missed it.

I used withRecordSeparator instead of withDelimiter to set the field separator.

This works as I expected:

public class Test {

    public static void main(String[] args) throws IOException {
        String DATA = "\"a\";12";
        CSVParser csvParser =    
        CSVFormat.EXCEL
            .withIgnoreEmptyLines()
            .withIgnoreHeaderCase()
            .withRecordSeparator('\n').withQuote('"')
            .withEscape('\\').withDelimeter(';').withTrim()
            .parse(new StringReader(DATA));
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM