开发者

Serialization and archiving object

开发者 https://www.devze.com 2023-01-30 06:56 出处:网络
I need to do the same operation but in one stream. May you help me, please? public static byte[] archivingAndSerialization(Object object){

I need to do the same operation but in one stream. May you help me, please?

public static byte[] archivingAndSerialization(Object object){

  ByteArrayOutputStream serializationByteArray = new ByteArrayOutputStream();
  ByteArrayOutputStream archvingByteArray = new ByteArrayOutputStream();
  try {

     ObjectOutputStream byteStream = new ObjectOutputStream(serializationByteArray);
     byteStream.writeObject(object);
     ZipOutputStream out = new ZipOutputStream(archvingByteArray);
     out.putNextEntry(new ZipEntry("str"));
     out.write(serializationByteArray.toByteArray());
     out.flush();
     out.close();

 开发者_如何学运维    } catch (IOException e) {
logger.error("Error while IOException!", e);
     }
  return archvingByteArray.toByteArray();
}


Try

ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos= new ObjectOutputStream(new DeflatingOutputStream(baos));
oos.writeObject(object);
oos.close();
return baos.toByteArray();

Note: Unless the object is medium to large in size, compressing it will make it bigger, as it add a header. ;)

To deserialize

ObjectInputStream ois = new ObjectInputStream(
    new InflatorInputStream(new ByteArrayInputStream(bytes)));
return ois.readObject();
0

精彩评论

暂无评论...
验证码 换一张
取 消