java序列化和反序列化放缓存的问题
2017-01-20 17:49
337 查看
在序列化和反序列化后,在放入缓存的时候不要用byte.tostring,直接放入byte字节数组,因为在序列化中,toString和“”.getByte()默认的编码是不一样的,这样就存在一个问题,序列化了,然后饭序列化不出来了。
java.io.StreamCorruptedException: invalid stream header:EFBFBDEF
java.io.StreamCorruptedException: invalid stream header:EFBFBDEF
The provided test code serializes an object to a ByteArrayOutputStream, converts the generated byte array into a string using the ByteArrayOutputStream.toString() method, converts the string back into a byte array using the String.getBytes() method, and then attempts to deserialize the object from the byte array using a ByteArrayInputStream. This procedure will in most cases fail because of the transformations that take place within ByteArrayOutputStream.toString() and String.getBytes(): in order to convert the contained sequence of bytes into a string, ByteArrayOutputStream.toString() decodes the bytes according to the default charset in effect; similarly, in order to convert the string back into a sequence of bytes, String.getBytes() encodes the characters according to the default charset. Converting bytes into characters and back again according to a given charset is generally not an identity-preserving operation. As the javadoc for the String(byte[], int, int) constructor (which is called by ByteArrayOutputStream.toString()) states, "the behavior ... when the given bytes are not valid in the default charset is unspecified". In the test case provided, the first two bytes of the serialization stream, 0xac and 0xed (see java.io.ObjectStreamConstants.STREAM_MAGIC), both get mapped to the character '?' since they are not valid in the default charset (ISO646-US in the JDK I'm running). The two '?' characters are then mapped back to the byte sequence 0x3f 0x3f in the reconstructed data stream, which do not constitute a valid header. The solution, from the perspective of the test case, is to use ByteArrayOutputStream.toByteArray() instead of toString(), which will yield the raw byte sequence; this can then be fed directly to the ByteArrayInputStream(byte[]) constructor.
byte[] serializedBean = SerializeUtils.serialize(new GiftBean(awardType),GiftBean.class); //礼包加到礼包池 Long l0 = cacheClusterClient.sadd(RedisKeyConstant.GIFT_BAG_POOL.getBytes(), serializedBean);
Set<byte[]> byteSet = cacheClusterClient.smembers(RedisKeyConstant.GIFT_BAG_POOL.getBytes());
相关文章推荐
- Java 序列化和反序列化工具类并解决StreamCorruptedException问题
- java 的序列化和反序列化的问题
- Java自定义序列化反序列化问题
- java 的序列化和反序列化的问题
- JAVA中序列化和反序列化中的静态成员问题
- java 的序列化和反序列化的问题
- Java 中的类为什么要实现序列化呢 / JAVA中序列化和反序列化中的静态成员问题
- java中的序列化和反序列化
- 【转,解决xml文件解析时提示无效的字符的问题】序列化,反序列化时低序位非打印 ASCII 字符的问题
- Java序列化和反序列化
- Java对象序列化和反序列化
- java 序列化 问题
- java Enum序列化问题
- 用 XStream 序列化/反序列化 XML 为 Java 对象
- Java Json/xml 序列化和反序列化 工具:JsonTools 和 simpleframework 附带实例
- 用 XStream 序列化/反序列化 XML 为 Java 对象(实例)
- java序列化和反序列化到底怎么回事?
- 序列化,反序列化时低序位非打印 ASCII 字符的问题
- java io (六) 对象序列化,反序列化 -- Serializable接口
- java对象的序列化和反序列化