简体   繁体   English

OpenCSV CSVWriter不会为空元素添加引号字符

[英]OpenCSV CSVWriter does not add quote character for null element

I have a requirement where i need to wrap all elements with quote character. 我有一个需要用引号将所有元素包装起来的要求。

I am using CSVWriter to writer the lines 我正在使用CSVWriter编写行

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. 当元素为空字符串时,它会包装引号;如果为null,则它不包含引号字符。

so mu output become like this. 所以亩输出变成这样。

"ABC",,"","DEF"

which i want like 我想要的

"ABC","","","DEF"

Here 2nd element is null and 3rd element is empty string. 在这里,第2个元素为null,第3个元素为空字符串。

Is there a way in OpenCSV to achieve this without manually intervention? OpenCSV中是否有一种无需手动干预即可实现的方法?

I don't think you can do that with CSVWriter in "auto" mode. 我认为您无法在“自动”模式下使用CSVWriter做到这一点。 Just assign manually empty "" value to null Strings in your code. 只需为代码中的null字符串手动分配空的""值即可。

As you don't want to change each row manually, maybe give univocity-parsers a go: 由于您不想手动更改每一行,因此可以尝试使用univocity解析器

//configure writer
CsvWriterSettings settings = new CsvWriterSettings();
settings.setQuoteAllFields(true);

If you are writing rows (or lists of rows): 如果要写行(或行列表):

//create writer with given config and output file
CsvWriter writer = new CsvWriter(new File(rptFileName), "UTF-8", settings);

//get your data from somewhere
List<Object[]> dataToWrite = getDataFromSomewhere();

//write everything.
writer.writeRowsAndClose(dataToWrite);

If you are dumping data from a ResultSet: 如果要从ResultSet转储数据:

ResultSet rs = getDataFromSomewhere();
new CsvRoutines(settings).write(rs, new File(rptFileName), "UTF-8");

That will do what you want, without manually changing your input. 这将完成您想要的操作,而无需手动更改输入。

Disclosure: I'm the author of this library, it's open-source and free (Apache 2.0 license) 披露:我是这个库的作者,它是开源的并且免费的(Apache 2.0许可证)

No the CSVWriter was purposefully designed this way so the CSVReader could differentiate between what is null and what is an empty string. 没有CSVWriter是以这种方式设计的,因此CSVReader可以区分什么是空字符串和什么是空字符串。 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. 更高版本中添加了CSVReaderNullFieldIndicator,以便用户可以确定什么为空(如果为空),但不会将其扩展到CSVWriter。 So you will have to do some manual intervention if you wish to stick with openCSV. 因此,如果您希望坚持使用openCSV,则必须进行一些手动干预。

If manual intervention is not possible you can use the Apache Commons libraries to help you out 如果无法进行手动干预,则可以使用Apache Commons库来帮助您

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. 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM