I'm currently trying to convert a JPEG image from the local java project directory to a byte array to send over a tcp connection.
This is currently how I'm converting my file to a byte array:
BufferedImage imageBuff = ImageIO.read(new File("res/image.jpg"));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(imageBuff, "JPEG", baos);
byte[] res = baos.toByteArray();
System.out.println(baos.toByteArray());
I can't seem to find a solid answer as to why this is happening, but every-time I convert it the data is not consistent:
System output:
[B@23f23303
[B@6299504b
[B@417f69df
What exactly is the byte array supposed to look like? It's clearly not working on the other side of the TCP connection for me unfortunately. I would think the output would have the same output each time it tries to convert it, no?
You're calling toString
on a byte[]
. Arrays don't override toString()
, so you're seeing the implementation in Object
:
The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:
getClass().getName() + '@' + Integer.toHexString(hashCode())
So in other words, that has nothing to do with the data within the byte array. Use Arrays.toString(byte[])
to get a string representation which actually looks reasonable - although you may find a hex conversion easier to read.
See more on this question at Stackoverflow