javabytearrayoutputstream

ByteArrayOutPutSteam to Byte[] not working as expected


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.


Solution

  • 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().