用Commons CSV解析CSV-引起IOException的引号中的引号

mho*_*r38 5 java csv double-quotes apache-commons-csv

我正在使用Commons CSV解析与电视节目有关的CSV内容。其中一个节目的节目名称带有双引号;

2010年9月10日116,6,2,29,“” JJ“(60分钟)”,“ http://www.tvmaze.com/episodes/4855/criminal-minds-6x02-jj

节目名称为“ JJ”(60分钟),该名称已用双引号引起来。这在封装的令牌和定界符之间抛出IOException java.io.IOException:(第1行)无效的char。

    ArrayList<String> allElements = new ArrayList<String>();
    CSVFormat csvFormat = CSVFormat.DEFAULT;
    CSVParser csvFileParser = new CSVParser(new StringReader(line), csvFormat);

    List<CSVRecord> csvRecords = null;

    csvRecords = csvFileParser.getRecords();

    for (CSVRecord record : csvRecords) {
        int length = record.size();
        for (int x = 0; x < length; x++) {
            allElements.add(record.get(x));
        }
    }

    csvFileParser.close();
    return allElements;
Run Code Online (Sandbox Code Playgroud)

CSVFormat.DEFAULT已设置withQuote('“')

我认为此CSV的格式不正确,应为““ JJ”“(60分钟)”“” JJ“(60分钟)”-但是有没有办法让通用CSV处理此问题,或者我需要手动修复此条目?

附加信息:其他显示名称在CSV条目中包含空格和逗号,并放在双引号中。

Jer*_*kes 5

这里的问题是引号没有正确转义。您的解析器无法处理。尝试univocity-parsers,因为这是Java的唯一解析器,我知道它可以处理带引号的值中的未转义的引号。它也比Commons CSV快4倍。试试这个代码:

//configure the parser to handle your situation
CsvParserSettings settings = new CsvParserSettings();
settings.setUnescapedQuoteHandling(STOP_AT_CLOSING_QUOTE);

//create the parser
CsvParser parser = new CsvParser(settings);

//parse your line
String[] out = parser.parseLine("116,6,2,29 Sep 10,\"\"JJ\" (60 min)\",\"http://www.tvmaze.com/episodes/4855/criminal-minds-6x02-jj\"");

for(String e : out){
    System.out.println(e);
}
Run Code Online (Sandbox Code Playgroud)

这将打印:

116
6
2
29 Sep 10
"JJ" (60 min)
http://www.tvmaze.com/episodes/4855/criminal-minds-6x02-jj
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你。

披露:我是该库的作者,它是开源的,并且免费(Apache 2.0许可证)