序列化流.

把对象以流的方式写入到文件中保存,叫做写对象,也叫对象的系列化 writeObject§
ObjectOutputStream 对象的序列化流
构造方法
ObjectOutputStream(OptputStream out) 创建指定的 ObjectOutputStream的objectOutputStream
参数
OptputStream out 字节输出流
特有的成员方法
void writeObject(object obj) 将指定的对象写入objectOutputStream中
使用步骤
创建objectOutputStream对象构造方法中传递字节输出流
使用objectOutputStream对象中的方法writeobject把对象写入到文件中
资源释放

ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("D:\\lianxi\\lianxi1\\oo.txt"));
oos.writeObject(new Jjcid("小美女",18));
oos.close();

注意:序列化和反序列化的时候会抛出没有序列化的异常
通过实现 Serializable接口以启动其序列化功能,未实现此接口的类无法序列化或反序列化

public class Jjcid implements Serializable {

把文件中保存的对象,以流的方式读取出来,叫做读对象,也叫对象的反序列化 readObject()
ObjectInputStream类
构造方法
ObjectInputStream(InputStream in)创建指定InputStream 读取objInputStream
参数
InputStream in 字节输入流
特有的成员方法
object readObj() 读取对象
使用步骤
创建ObjectInputStream对象,构造方法中传递字节输入流
使用ObjectInputStream对象中的方法readobject读取保存对象的文件
释放资源
使用读取出来的对象打印看看
注意:必须存在类对应的class文件
加上一个序列号代码
private static final long serialVersionUID = 1L;

ObjectInputStream ois = new ObjectInputStream(new FileInputStream("D:\\lianxi\\lianxi1\\oo.txt"));
Object o = ois.readObject();
ois.close();
Jjcid j = (Jjcid)o;
System.out.println(j);

序列化集合
当我们想在文件中保存多个对象的时候
可以把多个对象储存到一个集合中
对集合进行序列化和反序列化
步骤
创建一个Person对象的ArrayList集合
在ArrayList集合中存储Person对象
创建一个序列化流ObjectOutputStream对象
使用ObjectOutputStream对象中的方法writeObject对集合进行序列化
创建一个反序列化ObjectInputStream对象
使用反序列化ObjectInputStream对象方法readObject读取文件中保存的集合
把Object类型的集合转换成ArrayList类型集合
释放资源

ArrayList<Person> list = new ArrayList<>();
list.add(new Person("张三",18));
list.add(new Person("李四",19));
list.add(new Person("王五",17));
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("D:\\lianxi\\lianxi1\\1.txt"));
oos.writeObject(list);
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("D:\\lianxi\\lianxi1\\1.txt"));
Object o = ois.readObject();
ArrayList<Person> list1 = (ArrayList<Person>) o;
for (Person p : list1) {
    System.out.println(p);
}
ois.close();
oos.close();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值