SerializeUtil 序列化 java
import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author baoy * */ public class SerializeUtil { private static final Logger logger = LoggerFactory.getLogger(SerializeUtil.class); /** * 序列化 * @param object * @return */ public static byte[] serialize(Object object) { ObjectOutputStream oos = null; ByteArrayOutputStream baos = null; try { baos = new ByteArrayOutputStream(); oos = new ObjectOutputStream(baos); oos.writeObject(object); byte[] bytes = baos.toByteArray(); return bytes; } catch (Exception e) { } return null; } /** * 反序列化 * @param bytes * @return */ public static Object unserialize(byte[] bytes) { ByteArrayInputStream bais = null; try { bais = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bais); return ois.readObject(); } catch (Exception e) { } return null; } /** * 序列化存储list * @param list * @return * @throws IOException */ public static byte[] serializeList(List<Object> list) throws IOException { if (list == null) { throw new NullPointerException("Can't serialize null"); } byte[] rv = null; ByteArrayOutputStream bos = null; ObjectOutputStream os = null; try { bos = new ByteArrayOutputStream(); os = new ObjectOutputStream(bos); for (Object o : list) { os.writeObject(o); } os.writeObject(null); rv = bos.toByteArray(); } catch (IOException e) { throw new IllegalArgumentException("Non-serializable object", e); } finally { if (os != null) { os.close(); } if (bos != null) { bos.close(); } } return rv; } /** * 反序列化 * @param in * @return * @throws IOException */ public static List<Object> deserialize(byte[] in) throws IOException { List<Object> list = new ArrayList<Object>(); ByteArrayInputStream bis = null; ObjectInputStream is = null; try { if (in != null) { bis = new ByteArrayInputStream(in); is = new ObjectInputStream(bis); while (true) { Object object = is.readObject(); if (object == null) { break; } else { list.add(object); } } } } catch (IOException e) { logger.error("Caught IOException decoding %d bytes of data", in.length, e); } catch (ClassNotFoundException e) { logger.error("Caught CNFE decoding %d bytes of data", in.length, e); } finally { if (is != null) { is.close(); } if (bis != null) { bis.close(); } } return list; } }
捐助开发者
在兴趣的驱动下,写一个免费
的东西,有欣喜,也还有汗水,希望你喜欢我的作品,同时也能支持一下。 当然,有钱捧个钱场(支持支付宝和微信 以及扣扣群),没钱捧个人场,谢谢各位。
个人主页:http://knight-black-bob.iteye.com/
谢谢您的赞助,我会做的更好!