package test0811.io;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
class Person implements Serializable{// 创建类,对类的对象进行读取--实现了接口,所以可实现序列化了
private static final long serialVersionUID = -1335982255622818272L;//序列号,确保系列化的对象和反序列化的对象是一个
private String name;
private int age;
public Person(){}//构造方法,使构造起来容易一些
public Person(String name,int age){
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;
}
}
public class Test04 {
public static void main(String[] args) {
// 使用对象流进行读写(对对象进行读写,对象需要序列化)
// 将对象转换为字节序列进行持久化,就叫做序列化.(将内存中的对象存到硬盘上)
// 把字节序列恢复为对象,就叫反序列化.
// 所以,对对象进行读写,对象必须要能实现序列化.只要实现Serializable接口,此对象就能序列化.
FileInputStream fis = null;
ObjectInputStream ois = null;//输入流-读-反序列化
FileOutputStream fos = null;
ObjectOutputStream oos = null;//写入硬盘-序列化
Person zhangsan = new Person("张三",20);//创建对象
try {
fos = new FileOutputStream("file/c.txt");//连接文件
//创建文件输出流
oos = new ObjectOutputStream(fos);
oos.writeObject(zhangsan);//写入对象
oos.close();
fis = new FileInputStream("file/c.txt");//读文件
ois = new ObjectInputStream(fis);
Person result = (Person)ois.readObject();//Object转person类型
System.out.println(result.getName()+"\t"+result.getAge());
ois.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}