Let's say I have a serializable class AppMessage
.
I would like to transmit it as byte[]
over sockets to another machine where it is rebuilt from the bytes received.
How could I achieve this?
Write the contents of the object to the output stream using the writeObject() method of the ObjectOutputStream class. Flush the contents to the stream using the flush() method. Finally, convert the contents of the ByteArrayOutputStream to a byte array using the toByteArray() method.
of course u can serialize byte[] as JVM creates object of that byte array , and objects can be serialize.
Yes you can transfer a Serialized object via network because Java serialized object remains in form of bytes which can be transmitter via network.
Arrays in Java are serializable - thus Arrays of Arrays are serializable too. The objects they contain may not be, though, so check that the array's content is serializable - if not, make it so.
Prepare the byte array to send:
ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream out = null; try { out = new ObjectOutputStream(bos); out.writeObject(yourObject); out.flush(); byte[] yourBytes = bos.toByteArray(); ... } finally { try { bos.close(); } catch (IOException ex) { // ignore close exception } }
Create an object from a byte array:
ByteArrayInputStream bis = new ByteArrayInputStream(yourBytes); ObjectInput in = null; try { in = new ObjectInputStream(bis); Object o = in.readObject(); ... } finally { try { if (in != null) { in.close(); } } catch (IOException ex) { // ignore close exception } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With