• java序列化 SerializeUtil


    import java.io.ByteArrayInputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.Closeable;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    
    import cn.zsmy.constant.Constant;
    
    /**
     * @author shm
     */
    public class SerializeUtil {
    
        public static byte[] serialize(Object value) {
            if (value == 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);
                os.writeObject(value);
                os.close();
                bos.close();
                rv = bos.toByteArray();
            } catch (Exception e) {
                e.printStackTrace();
                Constant.MY_LOG.info("serialize error");
            } finally {
                close(os);
                close(bos);
            }
            return rv;
        }
    
        public static Object deserialize(byte[] in) {
            return deserialize(in, Object.class);
        }
    
        @SuppressWarnings("unchecked")
        public static <T> T deserialize(byte[] in, Class<T> requiredType) {
            Object rv = null;
            ByteArrayInputStream bis = null;
            ObjectInputStream is = null;
            try {
                if (in != null) {
                    bis = new ByteArrayInputStream(in);
                    is = new ObjectInputStream(bis);
                    rv = is.readObject();
                }
            } catch (Exception e) {
                e.printStackTrace();
                Constant.MY_LOG.info("deserialize error");
            } finally {
                close(is);
                close(bis);
            }
            return (T) rv;
        }
    
        private static void close(Closeable closeable) {
            if (closeable != null)
                try {
                    closeable.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    Constant.MY_LOG.info("close stream error");
                }
        }
    
    }
    

      

  • 相关阅读:
    5个示例带你学习AngularJS
    快速入门:十分钟学会Python
    Memcache知识点梳理
    用Phaser实现Flappy Bird 游戏
    7 个顶级的 HTML5 Canvas 动画赏析
    避坑宝典:如何选择HTML5游戏引擎
    电商平台10大商业与盈利模式
    【英文版本】Android开源项目分类汇总
    Android精品开源整理
    Android开源项目汇总【转】
  • 原文地址:https://www.cnblogs.com/shihaiming/p/5954011.html
Copyright © 2020-2023  润新知