需要在MySQL中保存Java对象。

说明:

  • 对象必须实现序列化
  • MySQL中对应字段设置为blob

将Java对象序列化为byte[]

public static byte[] obj2byte(Object obj) throws Exception {
    byte[] ret = null;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream out = new ObjectOutputStream(baos);
    out.writeObject(obj);
    out.close();
    ret = baos.toByteArray();
    baos.close();
    return ret;
}

将byte[]反序列化为Java对象

public static Object byte2obj(byte[] bytes) throws Exception {
    Object ret = null;
    ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
    ObjectInputStream in = new ObjectInputStream(bais);
    ret = in.readObject();
    in.close();
    return ret;
}

相关文章:

  • 2021-06-02
  • 2021-07-01
  • 2021-06-18
  • 2022-12-23
  • 2022-12-23
  • 2022-02-02
  • 2022-12-23
  • 2021-10-01
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-10-20
  • 2021-06-04
  • 2022-12-23
  • 2022-01-21
相关资源
相似解决方案