I want to write into a file using UTF-16 so I use PrintWriter(file,"UTF-16"), but then it deletes everything in the file, I could use FileWriter(file,true), but then it wouldn't be in UTF-16, and there apparently isn't a constructor for PrintWriter like PrintWriter(Writer,Charset,boolean append);
What should I do?
The JavaDoc for FileWriter
says:
The constructors of this class assume that the default character encoding and the default byte-buffer size are acceptable. To specify these values yourself, construct an
OutputStreamWriter
on aFileOutputStream
.
So you can do:
Writer writer = new PrintWriter(
new OutputStreamWriter(
new FileOutputStream(filename, true),
StandardCharsets.UTF16));
You might want to include BufferedOutputStream
in there too for maximum efficiency.