Given a byte array in UTF-8 encoding (as result of base64 decoding of a String) - what is please a correct way to write it to a file in UTF-8 encoding?
Is the following source code (writing the array byte by byte) correct?
OutputStreamWriter osw = new OutputStreamWriter(
new FileOutputStream(tmpFile), Charset.forName("UTF-8"));
for (byte b: buffer)
osw.write(b);
osw.close();
asked May 20, 2015 at 9:29
1 Answer 1
Don't use a Writer
. Just use the OutputStream
. A complete solution using try-with-resource looks as follows:
try (FileOutputStream fos = new FileOutputStream(tmpFile)) {
fos.write(buffer);
}
Or even better, as Jon points out below:
Files.write(Paths.get(tmpFile), buffer);
answered May 20, 2015 at 9:33
Sign up to request clarification or add additional context in comments.
4 Comments
Jon Skeet
Or
Files.write
to make it even simpler.Alexander Farber
When I use just OutputStream I get the error (later, when trying to use Efficient XML): Invalid byte 1 of 1-byte UTF-8 sequence. So I am trying to find a proper way to write the byte array to file in UTF-8 encoding
aioobe
But you said the array is in UTF-8 encoding, no? I think you should check your assumptions. Make sure the
buffer
is indeed proper UTF-8 and that it represents something Efficient XML can handle.Nitin Dandriyal
I think the problem is while reading in that case, create a buffer read and write simultaneously
lang-java
Base64
, but what was encoded with it? Are you sure they were strings? Were they Java strings? Were they byte arrays that were converted from strings? If you don't know what the actual objects were, it's going to be hard to print them as you don't even know they are strings. You can encode anything in base64, including images and sounds.