首页

java对象序列化及反序列化SerializeUtils工具类

标签:反序列化,Serializable,工具类,tools,java,常见,deserializeObject,serializeObject     发布时间:2016-09-29   

该工具类SerializeUtils通过serializeObject、deserializeObject静态方法分别对对象及字节码bytes进行序列号反序列化,具体内容如下

import java.io.ByteArrayInputStream;@b@import java.io.ByteArrayOutputStream;@b@import java.io.ObjectInputStream;@b@import java.io.ObjectOutputStream;@b@@b@public class SerializeUtils {@b@    @b@    public static byte[] serializeObject(Object obj) {        @b@        ByteArrayOutputStream byteOutputStream = null;@b@        ObjectOutputStream objectOutputStream = null;@b@        @b@        try{@b@            byteOutputStream = new ByteArrayOutputStream();@b@            objectOutputStream = new ObjectOutputStream(byteOutputStream);@b@            @b@            objectOutputStream.writeObject(obj);@b@            objectOutputStream.flush();@b@            @b@            return byteOutputStream.toByteArray();@b@        }catch(Exception e){@b@            e.printStackTrace();@b@        } finally {@b@            if(null != objectOutputStream){@b@                try{@b@                    objectOutputStream.close();@b@                    byteOutputStream.close();@b@                }catch(Exception e){@b@                    e.printStackTrace();@b@                }@b@            }@b@        }      @b@        @b@        return null;@b@    }@b@    @b@    public static Object deserializeObject(byte[] bytes) {@b@        ByteArrayInputStream byteInputStream = null;@b@        ObjectInputStream objectInputStream = null;@b@        @b@        try{@b@            byteInputStream = new ByteArrayInputStream(bytes);@b@            objectInputStream = new ObjectInputStream(byteInputStream);@b@            @b@            return objectInputStream.readObject();@b@            @b@        }catch(Exception e){@b@            e.printStackTrace();@b@        }finally {@b@            if(null != objectInputStream){@b@                try{@b@                    objectInputStream.close();@b@                    byteInputStream.close();@b@                }catch(Exception e){@b@                    e.printStackTrace();@b@                }@b@            }@b@        }@b@        return null;@b@    }@b@    @b@}