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.

Community
  • 1
  • 1
principal-ideal-domain
  • 3,998
  • 8
  • 36
  • 73

4 Answers4

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);
assylias
  • 321,522
  • 82
  • 660
  • 783
  • 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. – principal-ideal-domain May 18 '15 at 16:03
  • 1
    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. – the8472 May 18 '15 at 16:45
  • 1
    @principal-ideal-domain FYI, it was already answered in the question you linked http://stackoverflow.com/a/29456593/1587046 And then you could just look at the API to see that there is an overloaded version where you can specify the charset https://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#write(java.nio.file.Path,%20java.lang.Iterable,%20java.nio.charset.Charset,%20java.nio.file.OpenOption...) – Alexis C. May 18 '15 at 19:29
10
Path path = Paths.get("...");
Charset charset = StandardCharsets.UTF_8;
List<String> list = Collections.singletonList("...");
Files.write(path, charset, list, StandardOpenOption.APPEND);
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
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
}
Roger Gustavsson
  • 1,689
  • 10
  • 20
0

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

Mihai8
  • 3,113
  • 1
  • 21
  • 31