Search code examples
javaopencsv

Double Quotes getting duplicated while writing CSV file with OpenCSV


I am trying to write a simple CSVWriter code using OpenCSV library but having a strange issue with it.

Code:

public class Test {

    public static void main(String[] args) throws IOException {

       String[] header = {"ONE", "\"TWO\"", "\"THREE\"", "\"FOUR\""};

       CSVWriter writer = new CSVWriter(new FileWriter("C:/test.csv"), '|', CSVWriter.NO_QUOTE_CHARACTER);

       writer.writeNext(header);

       writer.flush();       
       writer.close();
    }
}

Expected Output:

ONE|"TWO"|"THREE"|"FOUR"

Real Output:

ONE|""TWO""|""THREE""|""FOUR""

As we can see there are Double Quotes surrounding TWO, THREE and FOUR but in the output the double quotes are duplicated.

I do not want this, have tried several options and constructor of CSVWriter class but did not able to sort this out.

Anyone faced similar issue or know a way out?

Thanks


Solution

  • Got it working, the below constructor worked:

    CSVWriter writer = new CSVWriter(new FileWriter("C:/test.csv"), '|', CSVWriter.NO_QUOTE_CHARACTER, CSVWriter.NO_ESCAPE_CHARACTER);
    

    Reason I see that the CSVWriter was considering " as a Escape Character by default and thus if it comes in String, it was will trying to Escape that " with DEFAULT_ESCAPE_CHARACTER which is not anything but " itself.

    By passing CSVWriter.NO_ESCAPE_CHARACTER, the Writer will not worry about checking if there are anything that needed to be in between Escapes.