简体   繁体   中英

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

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 .

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();

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