zoukankan      html  css  js  c++  java
  • 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");
                }
        }
    
    }
    

      

  • 相关阅读:
    webStorm 快捷键 + 浏览器
    Linux安装nodejs和npm
    jQuery页面滚动底部加载数据
    html跳转指定位置-利用锚点
    JavaScript自定义对象
    vue v-time指令封装(接口返回时间戳 在到日期转换)
    vue 之 引入elementUI(两步走)
    小白6步搞定vue脚手架创建项目
    vue 封装组件
    npm dev run 报错
  • 原文地址:https://www.cnblogs.com/shihaiming/p/5954011.html
Copyright © 2011-2022 走看看