Prevent opencsv from writing quotes to .csv file

Since this question pops up at the first place in google results when someone looks for OpenCSV and quotes issue, I'm going to add the newer solution here.

I'm using version 4.6 and it is indeed possible to skip the quotes, while keeping quotes in entires that contain separator char.

Sample code:

List<SomeCsvEntryTO> csvEntries = new ArrayList<>();
csvEntries.add(new SomeCsvEntryTO("sdf1", "sdf2"));
csvEntries.add(new SomeCsvEntryTO("hgh1", "hgh2;hghgh2"));

Writer writer = new FileWriter(filePath);
StatefulBeanToCsv<SomeCsvEntryTO> csvWriter = new StatefulBeanToCsvBuilder<SomeCsvEntryTO>(writer)
        .withSeparator(';')
        .withApplyQuotesToAll(false)
        .build();
csvWriter.write(csvEntries);
writer.close();

SomeCsvEntryTO:

public class SomeCsvEntryTO{

   @CsvBindByName(column = "sample1colname")
   private String sample1;

   @CsvBindByName(column = "sample2colname")
   private String sample2;
}

As you can see above, I am using semicolon as a separator and I do not change the quotechar. Just change the withApplyQuotesToAll to false.

This produces the following result:

SAMPLE1COLNAME;SAMPLE2COLNAME
sdf1;sdf2
hgh1;"hgh2;hghgh2"

Just to extend on Matten's answer, use the built-in characters in the CSVWriter to specify the quotechar. So your writer would look like the following:

CSVWriter writer = new CSVWriter(new FileWriter(fileName), CSVWriter.DEFAULT_SEPARATOR, CSVWriter.NO_QUOTE_CHARACTER);

Tags:

Java

Opencsv