You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Apache Commons CSV引号与转义字符相同时解析报错问题排查

问题描述

我有如下CSV文件记录:

firstname,lastname
"""amogh""",Kelula

其中firstname字段实际应为"amogh",因此使用双引号作为引号和转义字符,通过两个双引号转义。我使用Apache Commons CSV时配置了如下CSVFormat:

CSVFormat.DEFAULT.builder()
.setDelimiter(delimiter)
.setQuote(quoteCharacter) // quoteCharacter="
.setEscape(escapeCharacter) // escapeCharacter="
.setSkipHeaderRecord(false)
.setAllowMissingColumnNames(true)
.setNullString("")
.build();

解析含"""的行时出现错误,异常信息为:

java.io.IOException: (startline 2) EOF reached before encapsulated token finished.

其他解析器如PapaParser可正常解析该文件,请问我哪里配置错误?

解决方法

你的配置缺少启用引号内转义规则的关键设置。Apache Commons CSV默认不会自动识别双引号转义双引号的场景,需要显式配置QuoteMode并确保转义逻辑生效。

修正后的配置方案

  1. 显式设置QuoteMode
    添加setQuoteMode(QuoteMode.ALL)开启引号模式,让解析器正确处理引号内的转义字符。同时建议明确指定分隔符(避免delimiter变量未正确赋值的问题):
CSVFormat.DEFAULT.builder()
.setDelimiter(',') // 明确设置分隔符为逗号
.setQuote('"')
.setEscape('"')
.setQuoteMode(QuoteMode.ALL)
.setSkipHeaderRecord(false)
.setAllowMissingColumnNames(true)
.setNullString("")
.build();
  1. 直接使用预定义的RFC4180格式
    Apache Commons CSV提供的CSVFormat.RFC4180已经默认配置了双引号作为引号/转义字符,以及正确的QuoteMode,可直接适配你的场景:
CSVFormat format = CSVFormat.RFC4180
    .builder()
    .setSkipHeaderRecord(false)
    .setAllowMissingColumnNames(true)
    .setNullString("")
    .build();

内容的提问来源于stack exchange,提问作者Amogh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 00:07:13