OpenCSV CSVWriter does not add quote character for null element

大憨熊 提交于 2020-01-15 05:22:37

问题


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

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.

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.

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


回答1:


I don't think you can do that with CSVWriter in "auto" mode. Just assign manually empty "" value to null Strings in your code.




回答2:


As you don't want to change each row manually, maybe give univocity-parsers a go:

//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 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)




回答3:


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.

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. 


来源:https://stackoverflow.com/questions/44708379/opencsv-csvwriter-does-not-add-quote-character-for-null-element

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!