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.
In Java, we can append a string in an existing file using FileWriter which has an option to open a file in append mode. Java FileWriter class is used to write character-oriented data to a file. It is a character-oriented class that is used for file handling in Java.
You can use the FileWriter(String fileName, boolean append) constructor if you want to append data to file. Change your code to this: output = new BufferedWriter(new FileWriter(my_file_name, true));
Using FileOutputStream FileOutputStream is meant for writing streams of raw bytes such as image data. For writing streams of characters, consider using FileWriter . To append content to an existing file, open FileOutputStream in append mode by passing the second argument as true .
Path path = Paths.get("...");
Charset charset = StandardCharsets.UTF_8;
List<String> list = Collections.singletonList("...");
Files.write(path, charset, list, StandardOpenOption.APPEND);
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);
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With