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

Java使用CsvToBean解析分号分隔CSV时字段含分号解析失败如何解决

问题根因

你当前代码配置了withIgnoreQuotations(true),该配置会让解析器直接忽略你设定的单引号包裹规则,因此被单引号括起来的字段内部的分号仍然会被识别为字段分隔符,直接导致解析错位失败。

解决方案

1. 核心修复:关闭引号忽略配置

把withIgnoreQuotations(true)配置删除,或者显式设置为false,这样解析器就会识别单引号包裹的字段,将其内部的分号识别为普通文本,不会当做分隔符处理。
修改后的代码如下:

public static <T> List<T> getCsvData(String file, Class<T> clazz) throws IOException {
    try (FileReader fr = new FileReader(file)) {
        HeaderColumnNameMappingStrategy<T> strategy = new HeaderColumnNameMappingStrategy<>();
        strategy.setType(clazz);

        CsvToBean<T> csvToBean = new CsvToBeanBuilder<T>(fr)
                .withSeparator(';')
                .withQuoteChar('\'')
                // 移除withIgnoreQuotations(true)配置,该项默认值为false
                .withMappingStrategy(strategy).build();
        return csvToBean.parse();
    }
}

2. 可选兼容配置(适用于部分字段未加引号的场景)

如果你的CSV文件存在部分字段没有用单引号包裹的情况,可以额外增加.withIgnoreLeadingWhiteSpace(true)配置,避免字段前后的空格导致解析异常。

3. 异常兜底配置

如果需要兼容少量格式错误的行,不想因为个别行解析失败导致整个文件解析终止,可以增加.withThrowException(false)配置,解析错误的行会被跳过,不会抛出异常中断整体流程。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 11:54:04