1

I need to make a Byte[] out of a ByteArrayOutputStream, but this is not working. When I log the outcome of baos.toByteArray(); it only shows me eleven characters, no matter which file I try to upload, the log entry looks like this: [B@544641ab

This is the code:

    final ByteArrayOutputStream baos = new ByteArrayOutputStream(); // Stream to write to
    upload = new Upload();
    upload.setReceiver(new Upload.Receiver() {
        @Override
        public OutputStream receiveUpload(String filename, String mimeType) {

            return baos; // Return the output stream to write to
        }
    });
    upload.addSucceededListener(new Upload.SucceededListener() {
        @Override
        public void uploadSucceeded(Upload.SucceededEvent succeededEvent) {
        System.out.println ( baos.toByteArray().toString());
    }
});

Note: there is some Vaadin-specific code which is related to their upload-component. The upload component should provide an OutPutStream, which is correct so far.

user207421
  • 305,947
  • 44
  • 307
  • 483
Tobias Kuess
  • 739
  • 2
  • 14
  • 33

2 Answers2

1

Problem

[B@544641ab is the array type string ([B) combined with the identity hashcode of the byte array returned by baos.toByteArray(), not it's value.

Solution

Use Arrays.toString(baos.toByteArray()) instead of baos.toByteArray().toString(). You can also use baos.toString().

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Filipp Voronov
  • 4,077
  • 5
  • 25
  • 32
  • Okay, I was not aware of this. Thank you for the answer. So .toByteArray() is doing its job like it is supposed to do I guess? I will mark the answer as soon as the website let's me do so – Tobias Kuess Oct 11 '16 at 10:53
  • @TobiasKuess, yes, you're right – Filipp Voronov Oct 11 '16 at 10:55
  • No it isn't. It is the result of `Object.toString()`, which concatenates the object type (`[B`) with `"@"` and the result of `System.identityHashCode()`. – user207421 Oct 11 '16 at 11:05
  • @EJP, no, for `ByteArrayOutputStream` the `toString()` is overridden and returns _ buffer's contents into a string decoding bytes using the platform's default character set_ as described [here](https://docs.oracle.com/javase/7/docs/api/java/io/ByteArrayOutputStream.html) – Filipp Voronov Oct 11 '16 at 11:10
1

You are seeing the result of the default toString() of a byte[]. If you want to print it out properly, you could use Arrays.toString(byte[]):

System.out.println (Arrays.toString(baos.toByteArray());
Mureinik
  • 297,002
  • 52
  • 306
  • 350