对象序列化

记住一句话 序列化存储起来是用来 使用的, 不是用来看的

对象序列化的含义是什么?

 把对象数据存入到文件中去

对象序列化用了哪个流?

 对象字节输出流 ObjectOutputStream

 方法Public void writeObject(Object obj)

序列化对象的要求是什么样的?

 对象必须实现序列化接口

 

对象字节输出流

 

public class ObjectOutputStreamDome1 {
public static void main(String[] args) throws Exception{
//1. 创建学生对象
Student s = new Student("陈雷","chenlei","1314520",21);

//2. 对象序列化: 使用对象字节输出流包装字节输出流管道
OutputStream os = new FileOutputStream("E:\\idea_java_project\\io_project\\src\\dataCHEN.txt");
ObjectOutputStream oos = new ObjectOutputStream(os);

//3.直接调用序列化方法
oos.writeObject(s);

//4.释放资源
oos.close();
}
}
class Student implements Serializable { //对象如果要序列化, 必须要实现Serializable接口
private String name;
private String loginName;
private String passWord;
private int age;

----------------------------------------------------------
反序列化
/*
目标: 学会进行对象反序列化:使用对象字节流把文件中的对象数据恢复成内存中的Java对象
*/
public class ObjectInputStreamDemo2 {
public static void main(String[] args) throws Exception{
//1. 创建对象字节输入流管道 包装低级的字节输入流管道
InputStream is = new FileInputStream("E:\\idea_java_project\\io_project\\src\\dataCHEN.txt");
ObjectInputStream ois = new ObjectInputStream(is);

//2. 调用对象字节输入流方法
Student s = (Student) ois.readObject();
System.out.println(s);
}
}

 

posted on   我要当程序源  阅读(35)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示