Reputation: 100
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?
Upvotes: 1
Views: 876
Reputation: 41223
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.
Upvotes: 5
Reputation: 10127
You can do it by using
new PrintWriter(new OutputStreamWriter(new FileOutputStream(file, true), "UTF-16"));
Upvotes: 1
Reputation: 1500525
Use OutputStreamWriter
with a UTF-16 charset, wrapping a FileOutputStream
opened with append=true. Alternatives, use Files.newBufferedWriter
:
try (Writer writer = Files.newBufferedWriter(
Paths.of("filename.txt"),
StandardCharsets.UTF_16,
StandardOpenOption.APPEND)) {
...
}
Upvotes: 3