How to append text to file in Java 8 using specified Charset
Asked Answered
D

4

13

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.

Dentate answered 18/5, 2015 at 15:36 Comment(0)
G
26

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);
Guess answered 18/5, 2015 at 15:45 Comment(3)
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
B
10
Path path = Paths.get("...");
Charset charset = StandardCharsets.UTF_8;
List<String> list = Collections.singletonList("...");
Files.write(path, charset, list, StandardOpenOption.APPEND);
Balcom answered 18/5, 2015 at 15:46 Comment(1)
small typo: StandardOpenOption.APPENDGremlin
K
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
}
Kirt answered 18/5, 2015 at 15:50 Comment(0)
P
0

You can use append method from Guava Class Files. Also, you can take a look to java.nio.charset.Charset.

Paulie answered 18/5, 2015 at 15:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.