I have an object of type X which I want to convert into byte array before sending it to store in S3. Can anybody tell me how to do this? I appreciate your help.
String str = new String(byteArray, StandardCharsets. UTF_8); String class also has a method to convert a subset of the byte array to String. byte[] byteArray1 = { 80, 65, 78, 75, 65, 74 }; String str = new String(byteArray1, 0, 3, StandardCharsets.
The Ints class also has a toByteArray() method that can be used to convert an int value to a byte array: byte[] bytes = Ints. toByteArray(value);
What you want to do is called "serialization". There are several ways of doing it, but if you don't need anything fancy I think using the standard Java object serialization would do just fine.
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 to this that can be done. Not in the least the fact that you can only read/write one object per byte array, which might or might not be what you want.
Note that "Only objects that support the java.io.Serializable
interface can be written to streams" (see java.io.ObjectOutputStream
).
Since you might run into it, the continuous allocation and resizing of the java.io.ByteArrayOutputStream
might turn out to be quite the bottle neck. Depending on your threading model you might want to consider reusing some of the objects.
For serialization of objects that do not implement the Serializable
interface you either need to write your own serializer, for example using the read*/write* methods of java.io.DataOutputStream
and the get*/put* methods of java.nio.ByteBuffer
perhaps together with reflection, or pull in a third party dependency.
This site has a list and performance comparison of some serialization frameworks. Looking at the APIs it seems Kryo might fit what you need.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With