序列化和反序列化

2021年6月29日 9点热度 0条评论 来源: danmog
package com.****.web.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import org.apache.commons.codec.binary.Base64;

/** * 序列化对象Util * */
public final class SerializeUtil { 

    /** * 序列化对象 * @param object * @return * @throws IOException */
    public static String serializeObject(Object object) throws IOException{
       ByteArrayOutputStream baos = new ByteArrayOutputStream();
       ObjectOutputStream out = new ObjectOutputStream(baos);

       out.writeObject(object);
       out.flush();
       out.close();

       //加密
      return new Base64().encodeToString(baos.toByteArray());
    }

    /** * 反序列化对象 * @param buf * @return * @throws IOException * @throws ClassNotFoundException */
    public static Object deserializeObject(String  buf) throws IOException, ClassNotFoundException{
       Object object = null;
       ByteArrayInputStream bais = new ByteArrayInputStream(new Base64().decode(buf)); //解码
       ObjectInputStream in = new ObjectInputStream(bais);

       object = in.readObject();
       in.close();    
       return object;
    } 
}
    原文作者:danmog
    原文地址: https://blog.csdn.net/danmo1993/article/details/54894929
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系管理员进行删除。