OpenCSV CSVWriter不会为空元素添加引号字符 [英] OpenCSV CSVWriter does not add quote character for null element

查看:180
本文介绍了OpenCSV CSVWriter不会为空元素添加引号字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个需要用引号将所有元素包裹起来的要求。

I have a requirement where i need to wrap all elements with quote character.

我正在使用CSVWriter编写行

I am using CSVWriter to writer the lines

CSVWriter writer = new CSVWriter(new FileWriter(rptFileName),`CSVWriter.DEFAULT_SEPARATOR, CSVWriter.DEFAULT_QUOTE_CHARACTER);

当元素为空字符串时,它会包装引号;如果元素为空,则不会

When an element is a empty string then it wraps the quote and if it is null then it does not ad the quote character.

所以mu输出变成这样。

so mu output become like this.

ABC ,,, DEF

我想要的

ABC,,, DEF

此处第二个元素为空,第三个元素为空字符串。

Here 2nd element is null and 3rd element is empty string.

OpenCSV中是否有一种无需手动干预即可实现这一目标的方法?

Is there a way in OpenCSV to achieve this without manually intervention?

推荐答案

没有以这种方式故意设计CSVWriter,因此CSVReader可以区分空字符串和空字符串。更高版本中添加了CSVReaderNullFieldIndicator,以便用户可以确定什么为空(如果为空),但不会将其扩展到CSVWriter。因此,如果您希望坚持使用openCSV,则必须进行一些手动干预。

No the CSVWriter was purposefully designed this way so the CSVReader could differentiate between what is null and what is an empty string. Later versions added a CSVReaderNullFieldIndicator so the user could decide what was null (if there was a null) but the same was not extended to the CSVWriter. So you will have to do some manual intervention if you wish to stick with openCSV.

如果不可能进行手动干预,则可以使用Apache Commons库来帮助您

If manual intervention is not possible you can use the Apache Commons libraries to help you out

String[] copyArray = ArrayUtils.clone(originalValues);
for (int i = 0; i < copyArray.size; i++) {
   copyArray[i] = StringUtils.defaultString(copyArray[i]);
}

//  now use the CSVWriter to write the copyArray. 

这篇关于OpenCSV CSVWriter不会为空元素添加引号字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆