Search code examples
javafilestreamfileoutputstreamstringwriter

Write chinese characters from one file to another


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();

Solution

  • 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.

    Something like this:

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