What you want to do is called serialization . There are several ways to do this, but if you don't need anything interesting, I think using standard Java serialization would be very good.
Perhaps you could use something like this?
package com.example; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; public class Serializer { public static byte[] serialize(Object obj) throws IOException { try(ByteArrayOutputStream b = new ByteArrayOutputStream()){ try(ObjectOutputStream o = new ObjectOutputStream(b)){ o.writeObject(obj); } return b.toByteArray(); } } public static Object deserialize(byte[] bytes) throws IOException, ClassNotFoundException { try(ByteArrayInputStream b = new ByteArrayInputStream(bytes)){ try(ObjectInputStream o = new ObjectInputStream(b)){ return o.readObject(); } } } }
There are several improvements that can be made. Last but not least, the fact that you can read or write only one object per array of bytes, which may or may not be what you want.
Please note: "Only those objects that support the java.io.Serializable interface can be written to streams" (see java.io.ObjectOutputStream ).
As you may encounter this, the continuous distribution and resizing of java.io.ByteArrayOutputStream may turn out to be a pretty neck of the bottle. Depending on your stream model, you might consider reusing some objects.
To serialize objects that do not implement the Serializable interface, you need to either write your own serializer, for example, using the read * / write * java.io.DataOutputStream methods and the get * / put * java.nio.ByteBuffer methods, possibly together with reflection or draw in third party addiction.
This site lists and compares the performance of some serialization frameworks. Looking at the API, it seems Kryo might fit what you need.
Henrik Gustafsson Apr 29 2018-11-21T00: 00Z
source share