4

Does anyone have experience using opencsv in Java to write a csv file where only some of the elements need to be double quoted? The desired output I am looking to test is to make a file that would read:

1,"two",three

but when I try the following code

writer = new CSVWriter(new FileWriter("yourfile.csv"), ',',CSVWriter.NO_QUOTE_CHARACTER);
String[] entries = {"1","\"two\"","three"};
writer.writeNext(entries);
writer.close();

the following output occurs

1,""two"",three

Thoughts?

assylias
  • 321,522
  • 82
  • 660
  • 783
user2012652
  • 41
  • 1
  • 3

1 Answers1

5

These extra quotes are the escape characters used by OpenCSV. You need to use the overloaded constructor that allows you to turn off these:

writer = new CSVWriter(new FileWriter("yourfile.csv"), ',', 
           CSVWriter.NO_QUOTE_CHARACTER, CSVWriter.NO_ESCAPE_CHARACTER);
...

Output:

1,"two",three
Reimeus
  • 158,255
  • 15
  • 216
  • 276
  • 2
    the "no escape character" paramter will badly mess up with characters that need escaping in your String fields – seinecle Nov 20 '16 at 12:16