简体   繁体   中英

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 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?

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

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)

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. 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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