IO流,对象操作流ObjectOutputStream
该流可以将一个对象写出,或者读取一个对象到程序中,也就是执行了序列化和反序列化的操作。
1.创建一个PERSON对象实现Serializable接口。
public class Person implements Serializable {
private String name;
private int age;
public Person() {
super();
// TODO Auto-generated constructor stub
}
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 + "]";
}
2.进行对象序列化和反序列化。(就是将这两个对象存储到e.txt中,在从e.txt 中读取出来)
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class ObjectOutputStream {
public static void main(String[] args) throws IOException, ClassNotFoundException{
test1();
java.io.ObjectInputStream ois = new java.io.ObjectInputStream(new FileInputStream("e.txt"));
Person p1 = (Person) ois.readObject();
Person p2 = (Person) ois.readObject();
System.out.println(p1);
System.out.println(p2);
ois.close();
}
private static void test1() throws IOException, FileNotFoundException {
Person p1= new Person("张三",23);
Person p2= new Person("李三",23);
java.io.ObjectOutputStream oos = new java.io.ObjectOutputStream(new FileOutputStream("e.txt"));
oos.writeObject(p1);
oos.writeObject(p2);
oos.close();
}
}