In Java, the Serializable interface allows objects to be converted into a stream of bytes. This feature is crucial when objects need to be transmitted over a network or stored in a database.
To encode an object into a byte array, you can use the following steps:
To decode an object from a byte array, you can do the following:
Here are utility methods for serialization and deserialization:
Serialization:
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); } }
Deserialization:
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, you can easily convert objects to and from byte arrays, enabling you to transmit data over networks or persist it to storage.
The above is the detailed content of How Can I Serialize and Deserialize Java Objects to and from Byte Arrays?. For more information, please follow other related articles on the PHP Chinese website!