序列化整数收集到字节数组并将其反序列化
问题描述:
我需要将Collection<Integer>
的序列化和反序列化存储在Redis中,这需要byte[]
。我发现使用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();
}
而且现在的代码,我尝试使用反序列化:
Collection<Integer> deserializeIntegerCollection(byte[] bytes) {
ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
IntBuffer intBuffer = byteBuffer.asIntBuffer();
return asList(intBuffer.array());
}
但intBuffer.array()
抛出UnsupportedOperationException
。它有什么问题以及如何处理这个问题?
答
你可以像序列化它。 serializeIntegerCollection类必须实现可序列化。
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(list);
byte[] bytes = bos.toByteArray();
你可以反序列化一样。 deserializeIntegerCollectionclass
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes)); @SuppressWarnings("unchecked") Collection<Integer> collection= (Collection<Integer>) ois.readObject();
你有没有考虑咨询文件? – EJP