Appending to file in utf8

爷,独闯天下 提交于 2019-12-13 01:18:20

问题


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")
)

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

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.

Any thoughts?


回答1:


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



回答2:


try {
    BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("myFile.txt", true), "UTF-8"));
    out.write("Hello World");
    out.close();
} catch (IOException e) {
    e.printStackTrace();
}


来源:https://stackoverflow.com/questions/45614345/appending-to-file-in-utf8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!