【问题标题】:Serialize Integer collection to byte array and deserialize it back将整数集合序列化为字节数组并将其反序列化
【发布时间】:2017-05-04 09:52:53
【问题描述】:

我需要对Collection<Integer> 进行序列化和反序列化,以便将其存储在需要byte[] 的Redis 中。我找到了使用ByteBufferIntBuffer 进行序列化的代码:

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。它有什么问题以及如何处理?

【问题讨论】:

  • 您考虑过查阅文档吗?

标签: java arrays serialization


【解决方案1】:

你可以像这样序列化它。serializeIntegerCollection 类必须实现serializable


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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-05
    • 2021-03-25
    • 1970-01-01
    • 2017-04-07
    • 2011-09-29
    • 2022-08-16
    • 1970-01-01
    相关资源
    最近更新 更多