博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Java序列化和反序列化
阅读量:7113 次
发布时间:2019-06-28

本文共 2191 字,大约阅读时间需要 7 分钟。

简介


序列化是将实例化对象转换成字节数组,反序列化是将字节数组转换成对象。

实例


前提

使需要序列化的类实现Serializable接口

public class MyMessage implements Serializable

序列化

ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();    ObjectOutputStream objectOutputStream=new ObjectOutputStream(byteArrayOutputStream);    objectOutputStream.writeObject(object);    byte[] buffer=byteArrayOutputStream.toByteArray();    objectOutputStream.close();    byteArrayOutputStream.close();

反序列化

ByteArrayInputStream byteArrayInputStream=new ByteArrayInputStream(buffer);    ObjectInputStream objectInputStream=new ObjectInputStream(byteArrayInputStream);    Object object=objectInputStream.readObject();    objectInputStream.close();    byteArrayInputStream.close();

测试类源码

public class Test {    public static void main(String[] args) throws InterruptedException, IOException, ClassNotFoundException {        MyMessage message=new MyMessage("123","456","Hello",new Date());        File file=new File("F://temp");        FileOutputStream outputStream=new FileOutputStream(file);        ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();        ObjectOutputStream objectOutputStream=new ObjectOutputStream(byteArrayOutputStream);        objectOutputStream.writeObject(message);        outputStream.write(byteArrayOutputStream.toByteArray());        objectOutputStream.close();        byteArrayOutputStream.close();        outputStream.close();        System.out.println("OK!");        File file2=new File("F://temp");        FileInputStream inputStream=new FileInputStream(file);        byte[] buffer = new byte[inputStream.available()];        inputStream.read(buffer);        ByteArrayInputStream byteArrayInputStream=new ByteArrayInputStream(buffer);        ObjectInputStream objectInputStream=new ObjectInputStream(byteArrayInputStream);        MyMessage message2=(MyMessage) objectInputStream.readObject();        System.out.println(message2.toString());        objectInputStream.close();        byteArrayInputStream.close();        inputStream.close();    }}

测试结果为:

OK!
MyMessage [fromIp=123, toIp=456, text=Hello, image=null, date=Wed Sep 30 15:34:45 CST 2015]

转载于:https://www.cnblogs.com/pwc1996/p/5957870.html

你可能感兴趣的文章
简单聊聊DOM
查看>>
【JavaScript】JavaScript Array 对象(数组)
查看>>
github 上有趣又实用的前端项目(持续更新,欢迎补充)
查看>>
opencv python 直方图均衡化
查看>>
HotFrameLearning 热门框架学习(前言)
查看>>
git团队开发流程
查看>>
【Under-the-hood-ReactJS-Part6】React源码解读
查看>>
深入理解css之vertical-align
查看>>
Laravel事件
查看>>
matlab绘制peano(皮亚诺)曲线和koch(科赫曲线,雪花曲线)分形曲线
查看>>
使用pipenv代替virtualenv管理python包
查看>>
Docker零基础入门指南(四):Docker容器使用
查看>>
React 深入系列4:组件的生命周期
查看>>
Mybatis之设计模式之迭代器模式
查看>>
房间号生成器
查看>>
CentOS 6.8 安装vsftpd
查看>>
js设计模式 --- 装饰设计模式
查看>>
Flask源代码阅读笔记(一)——应用启动
查看>>
IOS精品源码,仿探探UIButton封装iOS提示弹框迅速引导页自定义导航栏
查看>>
setState的一个Synthetic Event Warning
查看>>