以 utf8 格式附加到文件 [英] Appending to file in utf8

查看:17
本文介绍了以 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天全站免登陆