繁体   English   中英

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

[英]How to append text to file in Java 8 using specified Charset

我正在寻找一种简单易用的解决方案,使用指定的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<String> lines = ...;
Files.write(log, lines, UTF_8, APPEND, CREATE);
Path path = Paths.get("...");
Charset charset = StandardCharsets.UTF_8;
List<String> 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM