- 对象流:ObjectOutputStream/ObjectInputStream
- 增强了缓冲区功能
- 增强了读写8种基本数据类型和字符串功能
- 增强了读写对象的功能:
- readObject() //从流中读取一个对象
- writeObject(Object obj) //向流中写入一个对象
- 使用流传输对象的过程称为序列化(写入)和反序列化(读取)
- 序列化类必须要实现Serializable接口
- 序列化类中对象属性要求实现Serializable接口
- 序列化版本号ID,保证序列化的类和反序列化的类是同一个类
- 使用transient(瞬间的)修饰属性,这个属性不能序列化
- 静态属性不能序列化
- 序列化多个对象可以借助集合来实现
//学生类
public class Student implements Serializable{
//序列化版本号ID:serialVersionUID
private static final long serialVersionUID = 1L;
private String name;
private int age;
//private transient int age; //该属性不能被序列化
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
public Student() {
}
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 "Student [name=" + name + ", age=" + age + "]";
}
}
序列化操作
//使用ObjectOutputStream实现对象的序列化
public class Test{
public static void main(String[] args) throws Exception{
//创建对象流
FileOutputStream fos = new FileOutputStream("D:\\stu.bin");
ObjectOutputStream ooj = new ObjectOutputStream(fos);
//序列化(写入操作):对象的类必须实现Serializable接口
Student zhangsan = new Student("张三";20);
Student lisi = new Student("李四";22);
//oos.writeObject(zhangsan);
//oos.writeObject(lisi);
ArrayList<Student> list = new ArrayList<Student>();
list.add(zhangsan);
list.add(lisi);
oos.writeObject(list);
oos.flush();
//关闭
oos.close();
}
}
反序列化操作
//使用ObjectInputStream实现对象的反序列化
public class Test{
public static void main(String[] args) throws Exception{
//创建对象流
FileInputStream fis = new FileInputStream("D:\\stu.bin");
ObjectInputStream ois = new ObjectInputStream(fis);
//反序列化(读取重构对象)
//Student s = (Student)ois.readObject(); //一次读一个对象
//Student s2 = (Student)ois.readObject();
//Student s3 = (Student)ois.readObject(); //读完再读就没有了,会报异常
ArrayList<Student> list = (ArrayList<Student>)ois.readObject();
//关闭
ois.close();
//System.out.println(s.toString()); //Student [name=张三, age=20]
//System.out.println(s2.toString()); //Student [name=李四, age=22]
System.out.println(list.toString());
}
}