[英]Serialize Integer collection to byte array and deserialize it back
I need to have serialization and deserialization of Collection<Integer>
for storing it in Redis which requires byte[]
. 我需要对
Collection<Integer>
进行序列化和反序列化,以将其存储在需要byte[]
Redis中。 I've found a code using ByteBuffer
and IntBuffer
for serialization: 我发现了使用
ByteBuffer
和IntBuffer
进行序列化的代码:
byte[] serializeIntegerCollection(Collection<Integer> collection) {
ByteBuffer byteBuffer = ByteBuffer.allocate(collection.size() * 4);
IntBuffer intBuffer = byteBuffer.asIntBuffer();
collection.forEach(intBuffer::put);
return byteBuffer.array();
}
And now the code I try to use for deserialization: 现在我尝试用于反序列化的代码:
Collection<Integer> deserializeIntegerCollection(byte[] bytes) {
ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
IntBuffer intBuffer = byteBuffer.asIntBuffer();
return asList(intBuffer.array());
}
But intBuffer.array()
throws UnsupportedOperationException
. 但是
intBuffer.array()
抛出UnsupportedOperationException
。 What's wrong with it and how to handle the issue? 它有什么问题以及如何处理该问题?
you can serialize it like. 您可以像序列化它。 serializeIntegerCollection class must implements serializable .
serializeIntegerCollection类必须实现serializable 。
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(list);
byte[] bytes = bos.toByteArray();
you can deserialize it like. 您可以像这样反序列化。 deserializeIntegerCollectionclass
deserializeIntegerCollectionclass
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes)); @SuppressWarnings("unchecked") Collection<Integer> collection= (Collection<Integer>) ois.readObject();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.