标签:
package com.cn.core.util; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; public class ObjectConvertor { /** * 序列化 * @param obj * @return */ public static byte[] serialize(Object obj) { if (obj == null) { throw new NullPointerException("Can‘t serialize null"); } byte[] object = null; ByteArrayOutputStream bos = null; ObjectOutputStream os = null; try { bos = new ByteArrayOutputStream(); os = new ObjectOutputStream(bos); os.writeObject(obj); object = bos.toByteArray(); } catch (IOException e) { throw new IllegalArgumentException("Non-serializable object", e); } finally { try { if (os != null) os.close(); if (bos != null) bos.close(); } catch (Exception ex) { ex.printStackTrace(); } } return object; } /** * 反序列化 * @param in * @return */ public static Object deserialize(byte[] bt) { Object object = null; ByteArrayInputStream bis = null; ObjectInputStream is = null; try { if (bt != null) { bis = new ByteArrayInputStream(bt); is = new ObjectInputStream(bis); object = is.readObject(); is.close(); bis.close(); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (is != null) is.close(); if (bis != null) bis.close(); } catch (Exception e2) { e2.printStackTrace(); } } return object; } }
标签:
原文地址:http://www.cnblogs.com/shell-blog/p/5845631.html