Java 如何将可序列化对象转换为一个字节数组呢?
下文笔者讲述可序列化对象与字节数组之间相互转换的方法分享,如下所示
定义一个ByteArrayOutputStream 对象 定义一个ObjectOutputStream对象 使用objectOutputStream的writeObject方法 即可将一个对象转换为字节数组 反之操作,即可实现字节数组转换为序列化对象例:对象转换为字节数组
ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream out = null; try { out = new ObjectOutputStream(bos); out.writeObject(yourObject); out.flush(); byte[] yourBytes = bos.toByteArray(); ... } finally { try { bos.close(); } catch (IOException ex) { // ignore close exception } }
字节数组创建对象
ByteArrayInputStream bis = new ByteArrayInputStream(yourBytes); ObjectInput in = null; try { in = new ObjectInputStream(bis); Object o = in.readObject(); ... } finally { try { if (in != null) { in.close(); } } catch (IOException ex) { // ignore close exception } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。