一,对象序列流
对象序列化:就是将对象保存到磁盘中,或者网络中传输对象
这种机制就是使用一个字节序列表示一个对象,该字节包含:对象的类型,对象的数据,对象中存储的属性等信息
字节序列写到文件之后,相当于文件中持久保存了一个对象的信息
反之,该字节序列还可以从文件中读取回来,重构对象,对它进行反序列化
要实现序列化和反序列化就要使用对象反序列化
-
对象序列化流:ObjectOutputSream
-
对象反序列化流:ObjectInputStream
对象序列化流:ObjectOutStream
-
将Java对象的原始数据和图形写入OutputStream。可以使用ObjectInputStream读取(重构)对象。可以通过使用流的文件来实现对象的持久存储。如果流是网络套接字流,则可以在另一个主机上或另一个进程中重构对象
构造方法:
- ObjectOutputStream(OutputStream out):创建一个写入指定的OutputStream的ObjectOutputStream
序列化对象的方法
- void wirteObject(Object ob):将指定的对象写入ObjectOutputStream
public static void main(String[]args)
{
ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("OtherStream\\oos.txt"));//在当前模块下创建一个写入指定的OutputStream的ObjectOutputStream
//假设我们创建了一个学生类Student,成员变量是String name;int age;
Student s=new Student("林林",18);
//在学生类要继承实现Serializable接口,这是由序列化流的特性决定的
oos.writeObject(s);//将指定的对象写入ObjectOutputSream
//释放资源
oos.close();
//运行后,在OtherStream\\oos.txt文件里写入s的序列化数据,我们不能直接这些序列化数据,就该对象反序列化。
}
//创建从指定的InputStream读取的ObjectInputStream
ObjectInputStream ois=new ObjectInputStream(new FileInputStream(("OtherStream\\oos.txt"));
//Object readObject():从ObjectInputStream读取一个对象
Object o=ois.read();
Student s=(Student) obj;//需要向下造型
System.out.println(s.getname()+","+s,getage());
//释放资源
ois.close();
二,对象反序列化流
对象反序列化流:ObjectOutputStream编写的原始数据和对象
- ObjectInputStream:反序列化先前使用ObjectOutputStream编写的原始数据和对象
构造方法
- ObjectInputStream(InputStream in):创建从指定的InputStream读取的ObjectInputStream
反序列化流的方法
- Object read():从ObjectInputStream读取一个对象
//创建从指定的InputStream读取的ObjectInputStream
ObjectInputStream ois=new ObjectInputStream(new FileInputStream(("OtherStream\\oos.txt"));
//Object readObject():从ObjectInputStream读取一个对象
Object o=ois.read();
Student s=(Student) obj;//需要向下造型
System.out.println(s.getname()+","+s,getage());
//释放资源
ois.close();