java - 将汉字从一个文件写入另一个文件

标签 java filestream fileoutputstream stringwriter

我有一个文件里面有汉字文本,我想把这些文本复制到另一个文件中。但文件输出与汉字混淆。请注意,在我的代码中,我已经使用“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();
}

关于java - 将汉字从一个文件写入另一个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15377756/

相关文章:

java - 如何在客户端-服务器应用程序中解决此 SocketException?

java - 如何发现对象是否包含设置为 0 的数字字段?

java - 使用 lambda 的嵌套过滤器

java - 如何将负 double 转换为二进制表示形式?

java - 异步任务上的多个notifyObservers()不起作用

c# - 读取时是否需要 Flush() FileStream?

c# - 如何在 C# 中读取和写入文件

c# - 使用 DeflateStream 读取与预期大小不匹配

java - 为什么我在文件中收到垃圾数据?

java - 按下 JButton 时将文件中的数字设置为 0