2013-03-13 87 views
1

我有一個帶有中文字符文本的文件,我想將這些文本複製到另一個文件中。但文件輸出與中文字符混淆。請注意,在我的代碼我使用「UTF8」作爲我的編碼已經:將中文字符從一個文件寫入另一個文件

BufferedReader br = new BufferedReader(new FileReader(inputXml)); 
StringBuilder sb = new StringBuilder(); 
String line = br.readLine(); 
while (line != null) { 
sb.append(line); 
sb.append("\n"); 
line = br.readLine(); 
} 
String everythingUpdate = sb.toString(); 

Writer out = new BufferedWriter(new OutputStreamWriter(
     new FileOutputStream(outputXml), "UTF8")); 

out.write(""); 
out.write(everythingUpdate); 
out.flush(); 
out.close(); 
+2

是你輸入文件中UTF-8編碼?當您檢查getEncoding()時,FileReader是否使用UTF-8?您是如何檢查輸出的,您的文本查看器是否支持UTF-8? – gerrytan 2013-03-13 05:36:08

+2

使用它使用的編碼讀取輸入文件。您可以在許多編輯器中檢查文件的編碼。 – longhua 2013-03-13 05:39:27

回答

2

的情況下,你不應該使用FileReader這樣的,因爲它不會讓你指定的輸入編碼。在FileInputStream上構建InputStreamReader

事情是這樣的:

BufferedReader br = 
     new BufferedReader(
      new InputStreamReader(
       new FileInputStream(inputXml), 
       "UTF8")); 
3

從@hyde答案是有效的,但我有兩個額外的音符,我將在下面的代碼中指出。

當然是由你的代碼重新組織你的需求

// Try with resource is used here to guarantee that the IO resources are properly closed 
// Your code does not do that properly, the input part is not closed at all 
// the output an in case of an exception, will not be closed as well 
try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(inputXML), "UTF-8")); 
    PrintWriter out = new PrintWriter(new OutputStreamWriter(new FileOutputStream(outputXML), "UTF8"))) { 
    String line = reader.readLine(); 

    while (line != null) { 
    out.println(""); 
    out.println(line); 

    // It is highly recommended to use the line separator and other such 
    // properties according to your host, so using System.getProperty("line.separator") 
    // will guarantee that you are using the proper line separator for your host 
    out.println(System.getProperty("line.separator")); 
    line = reader.readLine(); 
    } 
} catch (IOException e) { 
    e.printStackTrace(); 
} 
相關問題