3

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
6
  • It's duplicated (stackoverflow.com/questions/1001540/…) Commented May 20, 2015 at 9:37
  • 3
    If you already have a buffer of bytes you don't need a writer. A writer is for writing characters or Strings. Commented May 20, 2015 at 9:38
  • 2
    Based on your comment on the answer below, are you sure your array is in UTF-8 encoding? It will only be so if the original data that was encoded in base64 was in UTF-8 itself. What was the input of your base64 encode? Commented May 20, 2015 at 9:41
  • Some objects encoded with Base64.encode... (I know it's a stupid answer, but the source code is huge with 2500 Java files) Commented May 20, 2015 at 9:45
  • 2
    That is the code of 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. Commented May 20, 2015 at 9:53

1 Answer 1

5

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

Or Files.write to make it even simpler.
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
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.
I think the problem is while reading in that case, create a buffer read and write simultaneously

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.