如何使用指定的Charset将文本附加到Java 8中的文件

我正在寻找一种简单易用的解决方案,使用指定的Charset cs将文本附加到Java 8中的现有文件中。 我在这里找到的解决方案涉及标准的Charset ,这在我的情况下是不行的。

一种方法是使用接受Charset的重载版本的Files.write

 import static java.nio.charset.StandardCharsets.UTF_8; import static java.nio.file.StandardOpenOption.APPEND; import static java.nio.file.StandardOpenOption.CREATE; List lines = ...; Files.write(log, lines, UTF_8, APPEND, CREATE); 
 Path path = Paths.get("..."); Charset charset = StandardCharsets.UTF_8; List list = Collections.singletonList("..."); Files.write(path, charset, list, StandardOpenOption.APPEND); 

根据您指出的问题中接受的答案:

 try (PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream("myfile.txt", true), charset)))) { out.println("the text"); } catch (IOException e) { //exception handling left as an exercise for the reader } 

您可以使用Guava 类文件中的 append方法。 另外,您可以查看java.nio.charset.Charset 。