问题
I'm looking for an easy and save solution to append text to a existing file in Java 8 using a specified Charset cs
. The solution which I found here deals with the standard Charset
which is a no-go in my situation.
回答1:
One way it to use the overloaded version of 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);
回答2:
Path path = Paths.get("...");
Charset charset = StandardCharsets.UTF_8;
List<String> list = Collections.singletonList("...");
Files.write(path, charset, list, StandardOpenOption.APPEND);
回答3:
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
}
回答4:
You can use append method from Guava Class Files. Also, you can take a look to java.nio.charset.Charset.
来源:https://stackoverflow.com/questions/30307382/how-to-append-text-to-file-in-java-8-using-specified-charset