'ByteArrayOutPutSteam to Byte[] not working as expected [duplicate]
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 1:[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()
.
Solution 2:[2]
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());
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Mark Rotteveel |
Solution 2 | Mureinik |