2015-07-21 66 views
0
private static void write(String x, File file) 
    throws FileNotFoundException, IOException { 
    StringTokenizer tokenizer = new StringTokenizer(x) ; 
    FileOutputStream fop = new FileOutputStream(file, true); 
    while (tokenizer.hasMoreTokens()) { 
     fop.write(tokenizer.nextToken().toLowerCase().getBytes()); 
     fop.write(System.getProperty("line.separator").getBytes()); 
    } 
} 

關於上面的代碼,我在我的代碼中調用這個函數來在某些條件成立時寫一些單詞。但是,有時我會遇到一些奇怪的字符,例如â€,sé等。怎麼可能防止這樣的事情出現?異常字符已被寫入文件

回答

1

爲了將「字符」存儲在文件中,您必須將它們轉換爲字節序列。您可以直接使用getBytes(),也可以使用流編寫器爲您執行此操作。

不幸的是,有很多不同的方式來表示重音字符和原始ASCII集外的其他字符。您的代碼中的getBytes()會根據您的系統默認編碼返回一個此類表示。

當你看到奇怪的字符時,並不是說文件有什麼問題,而是你正在使用不同的編碼讀取文件。

你需要知道你在輸出中尋找什麼編碼,然後你可以告訴getBytes()產生該編碼。例如:

fop.write(tokenizer.nextToken().toLowerCase().getBytes("Windows-1252")); 
+1

一個完美的最後一行:) – lonesome

1

現在String.getBytes()使用默認編碼,每個平臺可能會改變。 您可以使用getBytes(charset),但更簡單的方法是使用字符串而不是字節的Writer。

對於所有後續寫入,OutputStreamWriter都可以進行一次編碼。

StringTokenizer tokenizer = new StringTokenizer(x) ; 
try (PrintWriter out = new PrintWriter(new BufferedWriter(
     new OutputStreamWriter(
      new FileOutputStream(file, true), 
      "UTF-8")))) { 
    while (tokenizer.hasMoreTokens()) { 
     out.println(tokenizer.nextToken().toLowerCase()); 
    } 
} 

您可能更喜歡"Windows-1252"的Windows Latin-1或其他東西。 UTF-8具有能夠結合所有腳本,西里爾語,希臘語,阿拉伯語的優勢。

+0

因爲只有一個能力來選擇一個答案,我upvoted你的好答案,而不是。 – lonesome