[英]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.我正在尝试使用
OpenCSV
库编写一个简单的CSVWriter
代码,但遇到了一个奇怪的问题。
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 .正如我们所看到的,TWO、THREE 和 FOUR 周围有双引号,但在输出中,双引号是重复的。
I do not want this, have tried several options and constructor of CSVWriter
class but did not able to sort this out.我不想要这个,已经尝试了
CSVWriter
类的几个选项和构造函数,但CSVWriter
这个问题。
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.原因我看到
CSVWriter
在默认情况下正在考虑"
作为转义字符,因此如果它出现在字符串中,它将尝试使用DEFAULT_ESCAPE_CHARACTER
来转义那个"
,它不是"
本身”。
By passing CSVWriter.NO_ESCAPE_CHARACTER
, the Writer will not worry about checking if there are anything that needed to be in between Escapes .通过传递
CSVWriter.NO_ESCAPE_CHARACTER
,Writer 不会担心检查Escapes之间是否需要任何东西。
If you are using com.opencsv.bean.StatefulBeanToCsv
builded by com.opencsv.bean.StatefulBeanToCsvBuilder
instead com.opencsv.CSVWriter
;如果您正在使用
com.opencsv.bean.StatefulBeanToCsv
建造由com.opencsv.bean.StatefulBeanToCsvBuilder
代替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()
您不能直接将选项设置为构造函数 params ,但您必须调用相应的方法来设置它:
.withQuotechar()
和.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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.