我正在使用以下代码段压缩可序列化对象:
private byte[] compressObject(Object obj) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPOutputStream gzipOut = new GZIPOutputStream(baos);
ObjectOutputStream objectOut = new ObjectOutputStream(gzipOut);
objectOut.writeObject(obj);
objectOut.close();
byte[] bytes = baos.toByteArray();
return bytes;
}
并使用以下代码段解压缩相同的对象:
private Object decompressObject(byte[] bytes) throws IOException,ClassNotFoundException {
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
GZIPInputStream gzipIn = new GZIPInputStream(bais);
ObjectInputStream objectIn = new ObjectInputStream(gzipIn);
Object obj = objectIn.readObject();
objectIn.close();
return obj;
}
在压缩对象之前和解压缩对象之后,我使用以下代码段计算 MD5 哈希:
public String getMD5Hash(Object obj) throws IOException, NoSuchAlgorithmException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput out = new ObjectOutputStream(bos);
out.writeObject(obj);
byte[] data = bos.toByteArray();
MessageDigest m = MessageDigest.getInstance("MD5");
m.update(data,0,data.length);
BigInteger i = new BigInteger(1,m.digest());
return String.format("%1$032X", i);
}
但是压缩前和压缩后计算的MD5 Hash不匹配。请建议如何在解压后获取对象。
谢谢。