如何使用open csv不使双引号加倍?

x3naxklr  于 2021-07-13  发布在  Java
关注(0)|答案(4)|浏览(438)

我用open csv(版本2.3)编写了一个csv文件。
在我的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类?

g2ieeal7

g2ieeal71#

逃避引用

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";
dgtucam1

dgtucam12#

如文件所述:https://docs.oracle.com/javase/tutorial/java/data/characters.html
只需使用:

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

ckocjqey3#

我找到了一个解决我问题的方法,它不是最好的,因为它不是通用的,但在我的情况下是可行的。我必须调用以下函数:

public void replaceDoubledQuotesInFile(File file) throws IOException {

    File tempFile = new File("temp.csv");
    FileWriter fw = new FileWriter(tempFile);

    Reader fr = new FileReader(file);
    BufferedReader br = new BufferedReader(fr);

    while(br.ready()) {

        String readenLine = br.readLine();

        if(readenLine.contains("\"\"")){

            String str1 = readenLine.replaceAll("\"\"", "!");
            String str2 = str1.replaceAll("!", "\"");

            fw.write(str2 + "\n");
            }
        else{
            fw.write(readenLine + "\n");}
    }

    fw.close();
    br.close();
    fr.close();

    file.delete();
    tempFile.renameTo(file);
}
brqmpdu1

brqmpdu14#

必须转义输入,但如果不希望转义输出,可以使用csvwriter.no\u escape\u字符创建writer。下面是一个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());
}

相关问题