In situations where you need to transmit Java objects across a network or store them in a binary format, converting them to byte arrays can be essential. Let's consider a scenario where we have a serializable class AppMessage. To send AppMessage instances over sockets to another machine and reconstruct them from the received bytes, we can follow these steps:
The code snippet for this process:
static byte[] serialize(final Object obj) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); try (ObjectOutputStream out = new ObjectOutputStream(bos)) { out.writeObject(obj); out.flush(); return bos.toByteArray(); } catch (Exception ex) { throw new RuntimeException(ex); } }
The corresponding code snippet:
static Object deserialize(byte[] bytes) { ByteArrayInputStream bis = new ByteArrayInputStream(bytes); try (ObjectInput in = new ObjectInputStream(bis)) { return in.readObject(); } catch (Exception ex) { throw new RuntimeException(ex); } }
With these methods in place, you can efficiently send serializable objects, such as AppMessage instances, over networks and reconstruct them on the receiving end.
The above is the detailed content of How to Convert Java Serializable Objects to Byte Arrays and Back?. For more information, please follow other related articles on the PHP Chinese website!