2017-09-26 86 views
0

我追加在Windows-1252編碼的文本轉換爲CSV這樣時間:不同的編碼我每次追加到一個CSV文件

public static final Charset CHARSET = Charset.forName("Windows-1252"); 


public void dumpToCSV(final List<String[]> content, 
         final char delimiter, 
         final String enc, 
         final int csvDays) { 

    File file = new File(Constants.CSV_FILENAME); 

    // Convert the Character Format before dumping to file: 
    try (
     OutputStreamWriter os = new OutputStreamWriter(
      new FileOutputStream(file, true), 
      CHARSET); 
     CSVWriter cw = new CSVWriter(os, delimiter)) { 

     // Remove old lines 
     clearCsvByDays(file, csvDays, Character.toString(delimiter)); 
     // Dump new content into file. 
     cw.writeAll(content); 
    } catch (IOException e) {} 
} 

private void clearCsvByDays(final File file, final int csvDays, final String delim) 
      throws IOException { 

    List<String> out = Files.lines(file.toPath(), CHARSET) 
          .filter(line -> mustFilter(line, csvDays, delim)) 
          .collect(Collectors.toList()); 
    Files.write(file.toPath(), out, 
       StandardOpenOption.WRITE, 
       StandardOpenOption.TRUNCATE_EXISTING); 
} 

第一寫入到文件,如預期的結果,這些字符是Windows-1252編碼,並且在目標程序中很好地顯示。

"ʳpⲠ t촴";"ADN";"26-09-2017";"0";"0";"0";"0"  <-- This result is fine. 

第二次轉儲,它追加UTF-8上的新數據,我不知道爲什麼。

"Éspáñà tëst";"ADN";"26-09-2017";"0";"0";"0";"0" <-- 2nd dump (new) 
"ʳpⲠ t촴";"ADN";"26-09-2017";"0";"0";"0";"0"  <-- 1st dump (old) 

第三場,它附加在另一個不同的編碼新的數據,但保持傾倒在Windows 1252的第一個正確的路線。

"Ãspáñà tëst";"ADN";"26-09-2017";"0";"0";"0";"0" <-- 3rd dump (new) 
"Éspáñà tëst";"ADN";"26-09-2017";"0";"0";"0";"0"  <-- 2nd dump (old) 
"ʳpⲠ t촴";"ADN";"26-09-2017";"0";"0";"0";"0"   <-- 1st dump (old) 

如果我繼續追加,每次都是不同的編碼。

爲什麼會發生這種情況,我該如何解決?

+0

哪裏'content'從何而來? – Berger

+0

第一個值來自.properties文件,因此它們必須手動填充。所有0值都來自WS響應。 – another

+0

您正在使用'CSVWriter'來編寫數據,但這不是標準的Java類。其實施中是否存在錯誤?很難說不知道代碼。 – toongeorges

回答

3

CSVWriter已被賦予正確的OutputStreamWriter。

並且在寫入時,Files.write也需要編碼。

Files.write(file.toPath(), out, CHARSET, 
    StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING); 

所以我懷疑黑客在別處:

new String(string.getBytes(...), ...) 
+0

我編輯的問題,因爲我找到了解決方案:P。感謝您的幫助。我打算髮布這個相同的答案:)。 – another

相關問題