我有一个里面有汉字文本的文件,我想将这些文本复制到另一个文件中。但文件输出与中文字符混乱。请注意,在我的代码中,我已经使用“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();
@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();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)