Apache commons CSV: quoted input doesn't work

流过昼夜 提交于 2019-12-11 08:15:29

问题


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.


回答1:


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));
    }

}



来源:https://stackoverflow.com/questions/38432743/apache-commons-csv-quoted-input-doesnt-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!