5

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

Asif
  • 4,980
  • 8
  • 38
  • 53

2 Answers2

2

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.

Asif
  • 4,980
  • 8
  • 38
  • 53
2

If you are using com.opencsv.bean.StatefulBeanToCsv builded by com.opencsv.bean.StatefulBeanToCsvBuilder instead com.opencsv.CSVWriter;

you can't set directly the options as constructor params, but you have to set it calling the respective methods: .withQuotechar() and .withEscapechar()

Like this:

StatefulBeanToCsvBuilder btcsvBuilder = new StatefulBeanToCsvBuilder(myOutputStreamWriter);
StatefulBeanToCsv btcsv = btcsvBuilder.withQuotechar(CSVWriter.NO_QUOTE_CHARACTER).withEscapechar(CSVWriter.NO_ESCAPE_CHARACTER).withMappingStrategy(myMapStrategy).withSeparator(',').build();
Mike D3ViD Tyson
  • 1,701
  • 1
  • 21
  • 31