如何使用指定的字符集将文本附加到 Java 8 中的文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30307382/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to append text to file in Java 8 using specified Charset
提问by principal-ideal-domain
回答by assylias
One way it to use the overloaded version of Files.write
that accepts a Charset:
使用Files.write
接受 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);
回答by Joop Eggen
Path path = Paths.get("...");
Charset charset = StandardCharsets.UTF_8;
List<String> list = Collections.singletonList("...");
Files.write(path, charset, list, StandardOpenOption.APPEND);
回答by Roger Gustavsson
Based on the accepted answer in the question you pointed at:
根据您指出的问题中已接受的答案:
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
}
回答by Mihai8
You can use append method from Guava Class Files. Also, you can take a look to java.nio.charset.Charset.
您可以使用 Guava Class Files 中的append 方法。此外,您可以查看java.nio.charset.Charset。