日志正文
|
||
序列化是指将一个对象序列化成字节流,便于存储或者网络传输;而反序列化恰好相反,将字节流,变回一个对象.我们平常用的比较多的是hessian序列化方式和java序列化方式,两种序列化方式的效率,以及序列化大小是不一样的,从测试结果看,hessian好一点.下面写了一个hessian序列化示例(没有文件IO与网络IO,纯粹序列化与反序列化): /** * 纯hessian序列化 * @param object * @return * @throws Exception */ public static byte[] serialize(Object object) throws Exception{ if(object==null){ throw new NullPointerException(); } ByteArrayOutputStream os = new ByteArrayOutputStream(); HessianSerializerOutput hessianOutput=new HessianSerializerOutput(os); hessianOutput.writeObject(object); return os.toByteArray(); } /** * 纯hessian反序列化 * @param bytes * @return * @throws Exception */ public static Object deserialize(byte[] bytes) throws Exception{ if(bytes==null){ throw new NullPointerException(); } ByteArrayInputStream is = new ByteArrayInputStream(bytes); HessianSerializerInput hessianInput=new HessianSerializerInput(is); Object object = hessianInput.readObject(); return object; } 另外一种常见的是java序列化方式: /** * java序列化 * @param obj * @return * @throws Exception */ public static byte[] serialize(Object obj) throws Exception { if (obj == null) throw new NullPointerException(); ByteArrayOutputStream os = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(os); out.writeObject(obj); return os.toByteArray(); } /** * java反序列化 * @param by * @return * @throws Exception */ public static Object deserialize(byte[] by) throws Exception { if (by == null) throw new NullPointerException(); ByteArrayInputStream is = new ByteArrayInputStream(by); ObjectInputStream in = new ObjectInputStream(is); return in.readObject(); }
最后修改于 2013-07-23 11:01
阅读(?)评论(0)
上一篇: java中的threadlocal变量测试
下一篇:URLClassLoader的用处
|
||
评论 想第一时间抢沙发么?