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

如何解决opencsv抛出的Unterminated quoted field CSV解析错误?

解决OpenCSV解析CSV时的"未终止引号字段"错误

问题场景

待解析的两行CSV数据:

"e90d18e0-ffe2-499c-9e46-3e7f15534ae8","Chandra Chekuri","40.09954372811568","-88.250470161438","Great part for running\0walking, tennis, pickle ball, volley ball, and Jarlings across!","Entertainment"
"cbef09e1-3e64-407a-b60d-22d6c6e1f589","Jingyi Yang","40.10999424873548","-88.2291090488434","Cocomero has the best ice cream.","Restaurant"

使用OpenCSV解析时抛出错误:

java.util.NoSuchElementException: Unterminated quoted field at end of CSV line. Beginning of lost text: [ and Jarlings across!,Entertainment cbef09e1-3e64-407a-b60d-22d6c6e1f589,Jingyi Yang,40.109994248...]

完整堆栈跟踪:

java.util.NoSuchElementException: Unterminated quoted field at 
end of CSV line. Beginning of lost text: [ and Jarlings 
across!,Entertainment
cbef09e1-3e64-407a-b60d-22d6c6e1f589,Jingyi Yang,40.109994248...]
    at com.opencsv.CSVIterator.next(CSVIterator.java:69)
    at com.opencsv.CSVIterator.next(CSVIterator.java:18)
Caused by: com.opencsv.exceptions.CsvMalformedLineException: Unterminated quoted field at end of CSV line. Beginning of lost text: [ and Jarlings across!,Entertainment
cbef09e1-3e64-407a-b60d-22d6c6e1f589,Jingyi Yang,40.109994248...]
    at com.opencsv.CSVReader.primeNextRecord(CSVReader.java:245)
    at com.opencsv.CSVReader.flexibleRead(CSVReader.java:610)
    at com.opencsv.CSVReader.readNext(CSVReader.java:204)
    at com.opencsv.CSVIterator.next(CSVIterator.java:67)
        ... 7 more

错误原因

核心问题是第一行CSV的描述字段中包含空字节(\0):

"Great part for running\0walking, tennis, pickle ball, volley ball, and Jarlings across!"

OpenCSV的默认解析器会将空字节视为特殊字符,干扰了它对引号字段边界的识别,导致解析器认为引号字段没有正确终止,进而抛出"未终止引号字段"的错误。

解决方法

1. 预处理CSV数据,移除空字节

在将数据传入OpenCSV解析前,先把所有空字节替换为合法字符(比如空格):

// 读取原始CSV内容
String rawCsv = Files.readString(Paths.get("your-file.csv"));
// 替换空字节为空格
String cleanedCsv = rawCsv.replace("\0", " ");
// 使用清理后的内容初始化CSVReader
CSVReader reader = new CSVReader(new StringReader(cleanedCsv));

2. 配置OpenCSV解析器兼容空字节(适用于OpenCSV 5.x及以上版本)

如果使用较新版本的OpenCSV,可以通过配置CSVParser来允许空字节:

CSVParser parser = new CSVParserBuilder()
    .withSeparator(',')
    .withQuoteChar('"')
    .withEscapeChar('\\')
    .withIgnoreQuotations(false)
    // 允许字段中包含空字节
    .withNullString("\0")
    .build();

CSVReader reader = new CSVReaderBuilder(new FileReader("your-file.csv"))
    .withCSVParser(parser)
    .build();

3. 确保CSV行分隔符正确

额外检查CSV文件的行分隔符是否为标准的\n或\r\n,避免两行数据被错误合并(不过本案例中主要诱因是空字节)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 23:50:29