2017-09-26 12 views
0

나는이 방법으로 CSV에로-1252 Windows에서 인코딩 된 텍스트를 추가하고에 추가 할 때마다 :다른 인코딩 내가 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'를 사용하고 있습니다 만 표준 자바 클래스는 아닙니다. 그 구현에 버그가 있습니까? 코드를 알지 못해도 말하기가 어렵습니다. – toongeorges

답변

3

CSVWriter에 올바른 OutputStreamWriter가 지정되었습니다.

그리고 쓰는 동안 Files.write에도 인코딩이 필요합니다.

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

그래서 해킹은 다른 곳에서 의심 :

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

해결책을 찾았 기 때문에 질문을 편집했습니다 : P. 도와 주셔서 감사합니다. 나는이 같은 대답을 게시 할 예정였다 :). – another