如何使用Open CSV将双引号加倍?

时间:2015-04-28 13:23:27

标签: java parsing csv opencsv

我使用Open CSV编写了一个CSV文件(版本2.3)。

在我的CSV文件中,我想写下以下一行: 我选择了一个英雄"这次冒险

但我找不到正确的配置,最后我的行打印在我的CSV文件中,如下所示: 我选择了一个""英雄""这次冒险

所以我的代码是:

CSVWriter writer = null;
writer  = new CSVWriter(outputStreamWriter,';',CSVWriter.NO_QUOTE_CHARACTER);

String[] lines = new String[4] ;

lines[0] = "Where is Brian" ;
lines[1] = "42" ;
lines[2] = "I choose a "hero" for this adventure" ;
lines[3] = "May the fourth be with you" ;

for (String line : lines ) {
    writer.writeNext(line );        
}

writer.close();

我怎样才能正确写下我的专线?

也许我必须使用CSVParser类?

3 个答案:

答案 0 :(得分:4)

转义引号

lines[2] = "I choose a \"hero\" for this adventure";

或使用单引号:

lines[2] = 'I choose a "hero" for this adventure';

或者

lines[2] = "I choose a 'hero' for this adventure";

答案 1 :(得分:1)

正如文件所说: https://docs.oracle.com/javase/tutorial/java/data/characters.html

只需使用:

lines[2] = "I choose a \"hero\" for this adventure" ;

答案 2 :(得分:0)

您必须转义输入,但如果您不希望输出转义,则可以使用CSVWriter.NO_ESCAPE_CHARACTER创建编写器。这是一个示例JUnit,它显示了我在说什么。

@Test
public void embeddedQuoteInString() {
  String[] line = {"Foo", "I choose a \\\"hero\\\" for this adventure"};
  StringWriter sw = new StringWriter();
  CSVWriter csvw = new CSVWriter(sw, CSVWriter.DEFAULT_SEPARATOR, CSVWriter.DEFAULT_QUOTE_CHARACTER, CSVWriter.NO_ESCAPE_CHARACTER);
  csvw.writeNext(line);
  assertEquals("\"Foo\",\"I choose a \\\"hero\\\" for this adventure\"\n", sw.toString());
}