zoukankan      html  css  js  c++  java
  • 对象序列化和反序列化

    首先要序列化的对象必须实现Serializable接口,序列化和反序列化实现代码如下:ByteUtils.java

    package com.zqgame.rabbitmq;
    
    import java.io.ByteArrayInputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    
    public class ByteUtils{
        /**
         * 序列化
         * @param o
         * @return
         * @throws Exception
         */
        public static byte[] toByteArray(Object o){
            ByteArrayOutputStream baos = null;
            ObjectOutputStream oos  = null;
            byte[] bs = null;
            try {
                baos = new ByteArrayOutputStream();
                oos = new ObjectOutputStream(baos);
                oos.writeObject(o);
                bs= baos.toByteArray();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }finally{
                try {
                    oos.close();
                    baos.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                
            }
            return bs;
        }
        /**
         * 反序列化
         * @param o
         * @return
         * @throws Exception
         */
        public static Object toObject(byte[] bytes){
             ByteArrayInputStream bais = null;
             ObjectInputStream ois = null;
             Object obj = null;
            try {
                bais = new ByteArrayInputStream(bytes);
                ois = new ObjectInputStream(bais);
                obj = ois.readObject();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }finally{
                try {
                    bais.close();
                    ois.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                
            }
             return obj;
        }
    }
  • 相关阅读:
    事务传播机制,搞懂。
    洛谷 P1553 数字反转(升级版) 题解
    洛谷 P1200 [USACO1.1]你的飞碟在这儿Your Ride Is Here 题解
    洛谷 P1055 ISBN号码 题解
    洛谷 P2141 珠心算测验 题解
    洛谷 P1047 校门外的树 题解
    洛谷 P1980 计数问题 题解
    洛谷 P1008 三连击 题解
    HDU 1013 题解
    HDU 1012 题解
  • 原文地址:https://www.cnblogs.com/zhougaojun/p/4547411.html
Copyright © 2011-2022 走看看