附加到utf8中的文件 [英] Appending to file in utf8

查看:79
本文介绍了附加到utf8中的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于项目,我需要使用UTF-8编码附加到文本文件中。
在研究过程中,我发现了两种可能性:

For a project I need to append to a textfile using UTF-8 encoding. During my research I found two possibilities:

BufferedWriter out = new BufferedWriter(
    new OutputStreamWriter(new FileOutputStream("file.txt), "UTF-8")
)

用UTF-8写入我的文件,但是它将覆盖它,而不是在文件已经存在的情况下追加到文件中。

This will write to my file in UTF-8, but it will overwrite it, rather than append to it if it already exist.

然后我找到了附加到现有代码的代码 FileWriter 中带有参数的文件,但这不会显式使用UTF-8,而是使用默认系统字符集:

Then I found the code to apend to an existing file with a parameter in the FileWriter, but this will not use UTF-8 explicitely, rather than use the default system character set:

BufferedWriter out = new BufferedWriter(new FileWriter("myfile.txt", true))

我现在需要同时定义编码和附加到文件的可能性。仅依靠系统编码或更改它不是一种选择。

I now need the possibility to define BOTH the encoding as well as appending to a file. Just rely on the system encoding or change this is not an option.

有什么想法吗?

推荐答案

您忘记添加 true 指向 FileOutputStream 构造函数:

You forgot to add the true paramter to the FileOutputStream constructor:

BufferedWriter out = new BufferedWriter(
    new OutputStreamWriter(
        new FileOutputStream("file.txt", true), // true to append
        StandardCharsets.UTF_8                  // Set encoding
    )
);

这篇关于附加到utf8中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆