java 将对象序列化到数据库中
序列化简单来说就是可以把对象直接存储起来,用的时候反序列化即可得到完整的对象。
1 设置mysql数据库字段 blob

2 给java 实现序列化标识,关键代码 implements Serializable
3 代码 序列化与反序列化
/** * 对象序列化成字节码数据 * * @param obj * @return */ public static byte[] setSerialize(Object obj) { ByteArrayOutputStream byteOutStream = new ByteArrayOutputStream( ); ObjectOutputStream oos = null; try { oos = new ObjectOutputStream(byteOutStream); oos.writeObject(obj); oos.close( ); return byteOutStream.toByteArray( ); } catch (Exception e) { e.printStackTrace( ); } finally { try { oos.close( ); } catch (IOException e) { e.printStackTrace( ); } } return null; } /** * 反序列化 字节码文件转对象 * * @param bytes * @return */ public static Object getSerialize(byte[] bytes) { ByteArrayInputStream byteInStream = new ByteArrayInputStream(bytes); ObjectInputStream ois = null; try { ois = new ObjectInputStream(byteInStream); return ois.readObject( ); } catch (Exception e) { e.printStackTrace( ); } finally { try { ois.close( ); } catch (IOException e) { e.printStackTrace( ); } } return null; }
4 结果

本文来自博客园,作者:lanwf,转载请注明原文链接:https://www.cnblogs.com/lccsdncnblogs/p/15819582.html

浙公网安备 33010602011771号