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

Java使用CSVReader读取含未闭合双引号的CSV被截断如何处理

问题核心原因

你尝试的replace/replaceAll语法本身没有问题,失效的核心原因是处理时机错误:调用readNext()时CSVReader已经按照CSV规则完成了字段拆分,你提供的行内容存在未闭合的双引号,会直接导致解析逻辑异常,拿到的line数组本身就是拆分错误的结果,后续再做引号替换也无法修复已经丢失的字段。

解决方案1:先预处理原始行再解析

不要直接调用readNext()读取拆分后的字段,先读取原始行文本移除所有双引号后,再送入CSVReader解析:

// 读取原始文本行
BufferedReader br = new BufferedReader(new FileReader("你的csv文件路径"));
String rawLine;
while ((rawLine = br.readLine()) != null) {
    // 先移除所有双引号
    String processedLine = rawLine.replace("\"", "");
    // 解析处理后的行,注意指定分隔符为分号
    CSVReader csvReader = new CSVReader(new StringReader(processedLine), ';');
    String[] line = csvReader.readNext();
    // 正常处理字段
    for(int i = 0; i<line.length; i++) {
        System.out.print(line[i]+" ");
    }
    csvReader.close();
}
br.close();

解决方案2:调整CSVReader配置适配异常格式

如果你使用的是OpenCSV,可以直接修改解析配置,忽略引号的特殊语义,不需要提前做文本替换:

// 自定义解析规则
CSVParser parser = new CSVParserBuilder()
    .withSeparator(';') // 指定分隔符为分号
    .withIgnoreQuotations(true) // 忽略引号的特殊语义,按普通字符处理
    .build();

// 初始化Reader时注入自定义规则
CSVReader reader = new CSVReaderBuilder(new FileReader("你的csv文件路径"))
    .withCSVParser(parser)
    .build();

String[] line;
while ((line = reader.readNext()) != null) {
    for(int i = 0; i<line.length; i++) {
        System.out.print(line[i]+" ");
    }
}
reader.close();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 01:06:05