首页 > 编程知识 正文

java中的序列化与反序列化,java中序列化和反序列化的作用

时间:2023-05-05 09:25:16 阅读:229152 作者:1150

1、序列化

//序列化为byte[]public static byte[] serialize(Object object) { ObjectOutputStream oos = null; ByteArrayOutputStream bos = null; try { bos = new ByteArrayOutputStream(); oos = new ObjectOutputStream(bos); oos.writeObject(object); byte[] b = bos.toByteArray(); return b; } catch (IOException e) { System.out.println("序列化失败 Exception:" + e.toString()); return null; } finally { try { if (oos != null) { oos.close(); } if (bos != null) { bos.close(); } } catch (IOException ex) { System.out.println("io could not close:" + ex.toString()); } }}

2、反序列化

//反序列化为Objectpublic static Object deserialize(byte[] bytes) { ByteArrayInputStream bais = null; try { // 反序列化 bais = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bais); return ois.readObject(); } catch (IOException | ClassNotFoundException e) { System.out.println("bytes Could not deserialize:" + e.toString()); return null; } finally { try { if (bais != null) { bais.close(); } } catch (IOException ex) { System.out.println("LogManage Could not serialize:" + ex.toString()); } }}

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。