serialization - Converting any object to a byte array in java -
i have object of type x want convert byte array before sending store in s3. can tell me how this? appreciate help.
what want called "serialization". there several ways of doing it, if don't need fancy think using standard java object serialization fine.
perhaps use 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 several improvements can done. not in least fact can read/write 1 object per byte array, might or might not want.
note "only objects support java.io.serializable
interface can written streams" (see java.io.objectoutputstream
).
since might run it, continuous allocation , resizing of java.io.bytearrayoutputstream
might turn out quite bottle neck. depending on threading model might want consider reusing of objects.
for serialization of objects not implement serializable
interface either need write own serializer, example using read*/write* methods of java.io.dataoutputstream
, get*/put* methods of java.nio.bytebuffer
perhaps reflection, or pull in third party dependency.
this site has list , performance comparison of serialization frameworks. looking @ apis seems kryo might fit need.
Comments
Post a Comment