* 1.什么是对象操作流
* 该流可以将一个对象写出, 或者读取一个对象到程序中. 也就是执行了序列化和反序列化的操作.
* 2.使用方式
* 写出: new ObjectOutputStream(OutputStream), writeObject()
可在person对象加上ID号
private static final long serialVersionUID = 1L;
解释:如果对person对象修改了属性等东西,没有存档,直接读取输出,会报错随机生成一个ID,不方便排查问题,如果修改了之后,先存档,在读取输出就不会有错误提示。
创建对象:
因为要序列化,所以要实现Serializable接口
package com.heima.bean;
import java.io.Serializable;
public class person implements Serializable{
private static final long serialVersionUID = 1L;
private String name;
private int age;
public person() {
super();
}
public person(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "person [name=" + name + ", age=" + age + "]";
}
}
对象写到文件代码:
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import com.heima.bean.person;
public class Demo3_ObjectOutPutStream {
public static void main(String[] args) throws IOException {
person pe1=new person("张三",23);
person pe2=new person("李四",24);
person pe3=new person("王五",25);
person pe4=new person("赵六",26);
ArrayList<person> arr=new ArrayList<>();
arr.add(pe1);
arr.add(pe2);
arr.add(pe3);
arr.add(pe4);
ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("f.txt"));
oos.writeObject(arr);//将整个集合一次写出
oos.close();
}
}
对象读取显示代码:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Array;
import java.util.ArrayList;
import com.heima.bean.person;
public class Demo4_ObjectInPutStream {
public static void main(String[] args) throws IOException, IOException, ClassNotFoundException {
// demo1();
ObjectInputStream ois=new ObjectInputStream(new FileInputStream("f.txt"));
ArrayList<person> arr=(ArrayList<person>) ois.readObject();//将整个集合对象,一次读取
for (person p : arr) {
System.out.println(p);
}
ois.close();
}
}