2017-05-04 68 views
0

我需要將Collection<Integer>的序列化和反序列化存儲在Redis中,這需要byte[]。我發現使用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。它有什麼問題以及如何處理這個問題?

+0

你有沒有考慮諮詢文件? – EJP

回答

-1

你可以像序列化它。 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();

相關問題