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.
How to append text to file in Java 8 using specified Charset
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);
Great. I was already thinking about that function but I didn't know that there is an OpenOption "APPEND". I just read "options - options specifying how the file is opened" and thought: No way, this function won't help me. –
Dentate
Knowing POSIX APIs,
open()
in this case, helps understanding such things. In the end java can only provide wrappers over system functions. It's also useful to know what you can fall back to via JNA if java isn't powerful enough. –
Advantageous @Dentate FYI, it was already answered in the question you linked https://mcmap.net/q/53921/-how-to-append-text-to-an-existing-file-in-java And then you could just look at the API to see that there is an overloaded version where you can specify the charset docs.oracle.com/javase/7/docs/api/java/nio/file/… –
Sacristy
Path path = Paths.get("...");
Charset charset = StandardCharsets.UTF_8;
List<String> list = Collections.singletonList("...");
Files.write(path, charset, list, StandardOpenOption.APPEND);
small typo: StandardOpenOption.APPEND –
Gremlin
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
}
You can use append method from Guava Class Files. Also, you can take a look to java.nio.charset.Charset.
© 2022 - 2024 — McMap. All rights reserved.