2015-04-28 54 views
0

我使用Open CSV編寫CSV文件(版本2.3)。如何在Open 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類?

+0

爲什麼不添加轉義字符 –

+0

它是什麼改變? – Fred37b

+0

我的確提出了Jordi&Marcin所說的相同的東西。在你的句子中打開一個「\」會告訴JVM它不應該被當作字符串的結尾 希望你能理解 –

回答

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"; 
+0

它根本不起作用,我嘗試了3種解決方案。也許在CSVWriter配置中有一個問題 – Fred37b

+0

你看看我評論過的鏈接嗎?http:// stackoverflow .com/questions/10451842/how-to-escape-comma-and-double-quote-at-same-time-for-csv-file可能有幫助 –

+0

是的,我訪問了你的鏈接,但它無法幫助我。得到了一個字符串列表,我搜索它是否包含「並嘗試用\替換它」但它不起作用。我還使用StringBuilder構建了一個字符串(使用.append(「\」「))。writer.writeNext(line);加雙引號。 – Fred37b

0

我找到一個解決我的問題,這不是最好的,因爲它不是通用的,但它在我的情況下工作。我要調用下面的函數:

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