java - 如何使用opencsv正确处理带引号的字符串中的逗号?
问题描述
我正在尝试读取包含带引号和不带引号的字符串的 csv 文件。
- 如果字符串被引用,它应该保存它的引号字符。
- 除此之外,如果字符串包含逗号,则不应拆分。
我已经尝试了多种方法,但到目前为止没有任何效果。
当前测试数据:
"field1 (with use of , we lose the other part)",some description
field2,"Dear %s, some text"
获取映射 bean 的第一个字段
预期结果:
"field1 (with use of , we lose the other part)"
field2
当前结果:
"field1 (with use of
field2
这是代码:
public class CsvToBeanReaderTest {
@Test
void shouldIncludeDoubleQuotes() {
String testData =
"\"field1 (with use of , we lose the other part)\",some description\n"
+
"field2,\"Dear %s, some text\"";
RFC4180ParserBuilder rfc4180ParserBuilder = new RFC4180ParserBuilder();
rfc4180ParserBuilder.withQuoteChar(ICSVWriter.NO_QUOTE_CHARACTER);
ICSVParser rfc4180Parser = rfc4180ParserBuilder.build();
CSVReaderBuilder builder = new CSVReaderBuilder(new StringReader(testData));
CSVReader reader = builder
.withCSVParser(rfc4180Parser)
.build();
List<TestClass> result = new CsvToBeanBuilder<TestClass>(reader)
.withType(TestClass.class)
.withEscapeChar('\"')
.build()
.parse();
result.forEach(testClass -> System.out.println(testClass.getField1()));
}
private List<TestClass> readTestData(String testData) {
return new CsvToBeanBuilder<TestClass>(new StringReader(testData))
.withType(TestClass.class)
.withSeparator(',')
.withSkipLines(0)
.withIgnoreEmptyLine(true)
.build()
.parse();
}
public static final class TestClass {
@CsvBindByPosition(position = 0)
private String field1;
@CsvBindByPosition(position = 1)
private String description;
public String toCsvFormat() {
return String.join(",",
field1,
description);
}
public String getField1() {
return field1;
}
}
}
我发现如果我评论或删除rfc4180ParserBuilder.withQuoteChar(ICSVWriter.NO_QUOTE_CHARACTER);
字符串将被正确解析,但我会丢失不应丢失的引号字符。有什么建议可以做吗?(我不希望打开其他 csv 库)
解决方案
推荐阅读
- c# - MSB4020:元素中“项目”属性的值“”
是无效的 - javascript - 如何将数据添加到firestore数据库子集合中的特定文档?
- dotnetnuke-9 - 如何在 DotNetNuke 9 中使用 crud 功能创建和安装 mvc 模块
- ionic3 - 如何从 Ionic 3 上传图像?
- android - startChooser() 方法和 startActivity() 的区别
- html - 调整大小时如何将元素垂直放置在 mat-list-item 上?
- php - Php将多维数组中的多个值与另一个多维数组进行比较
- json - JS:错误语法错误:JSON 中位置 0 的意外标记 u,Nativescript
- android - Gradle 同步失败:无法找到请求目标的有效证书路径
- mongodb - 如何在 MongoDb 中恢复特定的集合集