2010-12-14 43 views
1

我需要做同樣的操作,但在一個流。你能幫我嗎?序列化和歸檔對象

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(); 
} 

回答

1

嘗試

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

注:除非對象是中等大小,壓縮它將使更大,因爲它添加一個頭。 ;)

反序列化

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

謝謝,你幫了我很多 – darkAngel 2010-12-14 19:46:07