对象序列化和反序列化

首先要序列化的对象必须实现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;
    }
}

 

posted @ 2015-06-02 18:41  telzhou  阅读(247)  评论(0编辑  收藏  举报