2013-03-13 79 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(); 
} 
相关问题