序列化流.

简介: 序列化流.

把对象以流的方式写入到文件中保存,叫做写对象,也叫对象的系列化 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();


相关文章
|
存储 SQL 监控
管理Logstore
管理Logstore
288 1
|
域名解析 网络协议 Linux
|
Linux 虚拟化
CentOS7系统开机报错:you might want to save “/run/initramfs/rdsosreport.txt“ to a USB stick or /boot
CentOS7系统开机报错:you might want to save “/run/initramfs/rdsosreport.txt“ to a USB stick or /boot
1552 0
CentOS7系统开机报错:you might want to save “/run/initramfs/rdsosreport.txt“ to a USB stick or /boot
|
4天前
|
搜索推荐 编译器 Linux
一个可用于企业开发及通用跨平台的Makefile文件
一款适用于企业级开发的通用跨平台Makefile,支持C/C++混合编译、多目标输出(可执行文件、静态/动态库)、Release/Debug版本管理。配置简洁,仅需修改带`MF_CONFIGURE_`前缀的变量,支持脚本化配置与子Makefile管理,具备完善日志、错误提示和跨平台兼容性,附详细文档与示例,便于学习与集成。
293 116