ObjectOutputStream类
对象的序列化流
作用:把对象以流的方式写入到文件中保存
特有方法:
- writeObject( ) 将指定的对象写入 ObjectOutStream
public class Demo {
public static void main(String[] args) throws FileNotFoundException, IOException {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("D:\\备份\\main.txt"));
oos.writeObject(new Person("保罗乔治",31));
oos.close();
}
}
public class Person implements Serializable{
private String name;
private int age;
public Person() {
// TODO Auto-generated constructor stub
}
public Person(String name,int age) {
this.name = name;
this.age = age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
注意事项:
一定要进行实现 Serializable 否则会出现 未实例异常
对象的反序列化
作用:把对象以流的方式从文件中读取出来
特有方法:
- readObject( ) 从ObjectOutStream中读取对象
public class Demo {
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
ObjectInputStream oos = new ObjectInputStream(new FileInputStream("D:\\备份\\main.txt"));
Object o = oos.readObject();
oos.close();
System.out.print(o);
}
}
运行结果(由于未重写toString方法所以打印出为地址):
反序列化前提: 也需要这个类实现 Serializable