将汉字从一个文件写入另一个文件
问题描述:
我有一个带有中文字符文本的文件,我想将这些文本复制到另一个文件中.但是文件输出与汉字混乱.请注意,在我的代码中,我已经在使用"UTF8"作为编码了:
I have a file with Chinese characters text inside, I want to copy those text over to another file. But the file output messes with the chinese characters. Notice that in my code I am using "UTF8" as my encoding already:
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();
答
您不应使用 FileInputStream .
You should not use FileReader in a case like this, as it does not let you specify input encoding. Construct an InputStreamReader on a FileInputStream.
类似这样的东西:
BufferedReader br =
new BufferedReader(
new InputStreamReader(
new FileInputStream(inputXml),
"UTF8"));