views:

343

answers:

1

(im new to java)

from my searches for Serialization in Java most of the examples document writing to a file or reading from one.

my question is lets 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 bytes received.

how could i achieve this please?

thanks for your insight in advance.

+5  A: 

Prepare bytes to send:

ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput out = new ObjectOutputStream(bos);   
out.writeObject(yourObject);
byte[] yourBytes = bos.toByteArray(); 

Create object from bytes:

ByteArrayIntputSream bis = new ByteArrayInputStream(yourBytes);
ObjectInput in = new ObjectInputStream(bis);
Object o = in.readObject();
Taylor Leese
This isn't a complete answer, it just tells how to transform `Serializable` class into byte array but the question itself covers the whole topic including RMI, object construction and deconstruction, serialization mechanisms and versions etc. etc.
Esko
That's not how I read the question. To me it sounds like his problem is how to convert the object to a byte[] -- not how to send it.
Taylor Leese
Taylor: yes you got it right. i want to turn the object into a byte[] and transmit it. can you please also provide the code regarding how to turn this byte[] into an object please?
iEisenhower
@ikurtz - done.
Taylor Leese
Taylor: for create object from bytes, i dont see the byte[] from which the object is being constructed?
iEisenhower
@ikurtz - I just added that. Left it out on accident.
Taylor Leese
thanks a great deal. :)
iEisenhower
@ikurtz - no problem
Taylor Leese