Writing a byte array to a UTF8 encoded file

Given a UTF-8 encoded byte array (resulting in base64 decoding the string ) - what is the correct way to write this file in UTF-8 encoding please?

Is the following source code correct (writing array byte by byte)?

OutputStreamWriter osw = new OutputStreamWriter(
    new FileOutputStream(tmpFile), Charset.forName("UTF-8"));
for (byte b: buffer)
    osw.write(b);
osw.close();

      

+3


source to share


1 answer


Do not use Writer

. Just use OutputStream

. A complete solution using try-with-resource looks like this:

try (FileOutputStream fos = new FileOutputStream(tmpFile)) {
    fos.write(buffer);
}

      



Or even better, as John points out:

Files.write(Paths.get(tmpFile), buffer);

      

+4


source







All Articles