Writing byte array to an UTF8-encoded file

11,649

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);
Share:
11,649
Alexander Farber
Author by

Alexander Farber

/me/likes: Java, С#, Perl, PHP, JavaScript, PostgreSQL, Linux, Azure /me/speaks: German, English, Russian /me/learns: https://github.com/afarber/android-questions https://github.com/afarber/unity-questions https://github.com/afarber/ios-questions

Updated on July 13, 2022

Comments

  • Alexander Farber
    Alexander Farber almost 2 years

    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();
    
  • Jon Skeet
    Jon Skeet almost 9 years
    Or Files.write to make it even simpler.
  • Alexander Farber
    Alexander Farber almost 9 years
    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
    aioobe almost 9 years
    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
    Nitin Dandriyal almost 9 years
    I think the problem is while reading in that case, create a buffer read and write simultaneously