[英]OpenCSV quoting null values
Using the OpenCSV library, calling StatefulBeanToCsv.write()
my null values are being wrapped in quotes.使用 OpenCSV 库,调用StatefulBeanToCsv.write()
我的空值被包裹在引号中。
Example:例子:
String[] columns = new String[] {
"Col1",
"Col2",
"Col3"
};
ColumnPositionMappingStrategy strat = new ColumnPositionMappingStrategy();
strat.setColumnMapping(columns);
Writer writer = new FileWriter(outputFilePath);
StatefulBeanToCsv beanToCsv = new StatefulBeanToCsvBuilder(writer)
.withMappingStrategy(strat)
.build();
beanToCsv.write(items);
writer.close();
will produce:将产生:
1,"",3
When I expect:当我期望:
"1",,"3"
I have not set quotes to all fields via .withApplyQuotesToAll(true)
.我没有通过.withApplyQuotesToAll(true)
为所有字段设置引号。
If I do use .withApplyQuotesToAll(true)
, I end up with如果我确实使用.withApplyQuotesToAll(true)
,我最终会得到
"1","","3"
At one point, it appears the library the opposite of this:有一次,图书馆似乎与此相反:
OpenCSV CSVWriter does not add quote character for null element OpenCSV CSVWriter 不会为空元素添加引号字符
How can I null values written as a blank/empty value, rather than an empty string?如何将空值写入空白/空值而不是空字符串?
It looks like the method that you mentioned not calling actually takes a boolean.看起来你提到的没有调用的方法实际上是一个布尔值。 Have you tried the following?您是否尝试过以下方法?
.withApplyQuotesToAll(false)
There is a way to do that.有一种方法可以做到这一点。 Setting .withApplyQuotesToAll(false)
tells OpenCSV to only quote elements that has special characters, but we can change what OpenCSV understands by that, extending CSVWrite class like this:设置.withApplyQuotesToAll(false)
告诉 OpenCSV 只引用具有特殊字符的元素,但我们可以改变 OpenCSV 理解的内容,像这样扩展 CSVWrite 类:
public class CustomCsvWriter extends CSVWriter {
public CustomCsvWriter(Writer writer) {
super(writer);
}
@Override
protected boolean stringContainsSpecialCharacters(String line) {
return !line.isEmpty();
}
}
So, you can create a StatefulBeanToCsv like this:因此,您可以像这样创建一个 StatefulBeanToCsv:
new StatefulBeanToCsvBuilder<>(new CustomCsvWriter(writer))
.withMappingStrategy(strat)
.withApplyQuotesToAll(false)
.build();
Tested with OpenCSV 5.3使用 OpenCSV 5.3 测试
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.