Reputation: 5038
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
Upvotes: 5
Views: 4047
Reputation: 1771
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();
Upvotes: 2
Reputation: 5038
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.
Upvotes: 2