Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Serializable Object to Byte Array

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?

like image 300
iTEgg Avatar asked May 14 '10 18:05

iTEgg


People also ask

How do I turn a object into a byte array?

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.

Can you serialize a byte array?

of course u can serialize byte[] as JVM creates object of that byte array , and objects can be serialize.

Can a serialized object be transferred over a network?

Yes you can transfer a Serialized object via network because Java serialized object remains in form of bytes which can be transmitter via network.

Can arrays be serialized in Java?

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.


1 Answers

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   } } 
like image 102
Taylor Leese Avatar answered Sep 17 '22 03:09

Taylor Leese