Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append text to file in Java 8 using specified Charset

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.

like image 943
principal-ideal-domain Avatar asked May 18 '15 15:05

principal-ideal-domain


People also ask

How do you append data to an existing file in Java?

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.

How do you add a new line of text to an existing file 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));

How do I append a file with FileOutputStream?

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 .


3 Answers

Path path = Paths.get("...");
Charset charset = StandardCharsets.UTF_8;
List<String> list = Collections.singletonList("...");
Files.write(path, charset, list, StandardOpenOption.APPEND);
like image 138
Joop Eggen Avatar answered Oct 19 '22 17:10

Joop Eggen


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);
like image 42
assylias Avatar answered Oct 19 '22 18:10

assylias


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
}
like image 3
Roger Gustavsson Avatar answered Oct 19 '22 18:10

Roger Gustavsson