Alexander Farber
Alexander Farber

Reputation: 22988

Writing byte array to an UTF8-encoded file

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();

Upvotes: 3

Views: 13944

Answers (1)

aioobe
aioobe

Reputation: 421040

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);

Upvotes: 5

Related Questions