我正在寻找一种简单易用的解决方案,使用指定的Charset cs
将文本附加到Java 8中的现有文件中。我找到的解决方案here处理标准Charset
,这在我的情况下是不行的。
答案 0 :(得分:20)
使用Files.write
that accepts a Charset的重载版本的一种方法:
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);
答案 1 :(得分:8)
Path path = Paths.get("...");
Charset charset = StandardCharsets.UTF_8;
List<String> list = Collections.singletonList("...");
Files.write(path, charset, list, StandardOpenOption.APPEND);
答案 2 :(得分:3)
根据您指出的问题中接受的答案:
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
}
答案 3 :(得分:0)
您可以使用Guava Class Files中的append方法。此外,您可以查看java.nio.charset.Charset。