/**
* @Description: 序列化/反序列化工具类
* @Author: 码上得天下
* @Date: 2019-12-24
*/
public class SerializeUtils {
private static Logger logger = LoggerFactory.getLogger(SerializeUtils.class);
private static final String ERROR_MSG_SERIALIZE = "序列化异常";
private static final String ERROR_MSG_DESERIALIZE = "反序列化异常";
public static String serialize(Object obj) throws Exception {
ByteArrayOutputStream baos = null;
ObjectOutputStream oos = null;
try {
// 输出序列化对象到字节流
baos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(baos);
oos.writeObject(obj);
oos.flush();
return new String(Base64.encodeBase64(baos.toByteArray()), "ASCII");
} catch (Exception e) {
logger.info("序列化异常:", e);
throw new Exception(ERROR_MSG_SERIALIZE);
} finally {
if (baos != null) {
baos.close();
}
if (oos != null) {
oos.close();
}
}
}
public static Object deserialize(String ser) throws Exception {
ByteArrayInputStream bais = null;
ObjectInputStream ois = null;
try {
bais = new ByteArrayInputStream(Base64.decodeBase64(ser.getBytes("ASCII")));
ois = new ObjectInputStream(bais);
return ois.readObject();
} catch (Exception e) {
logger.info("反序列化异常:", e);
throw new Exception(ERROR_MSG_DESERIALIZE);
} finally {
if (bais != null) {
bais.close();
}
if (ois != null) {
ois.close();
}
}
}
}