package cn.itsource.Homework_01;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class Test2 {
public static void main(String[] args) throws Exception {
/*
*对象流:就是将一个对象永久保存到磁盘并且随时可以读取出来
*ObjectInpuStream :从文件中读取数据
*ObjectoutpuStream :从内存中,代码中 将对象存入磁盘
* */
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("F:/xx/student.txt"));
Student sut1 = new Student("郭靖", 55);
Student sut2 = new Student("杨过", 33);
oos.writeObject(sut1);
oos.writeObject(sut2);
oos.writeObject(null);//用来判断是否达到文件末尾
//从文件中读取对象
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("f:/xx/student.txt"));
//单个对象的读取
/*Student stu1= (Student)ois.readObject();
System.out.println(stu1);
Student stu2= (Student)ois.readObject();
System.out.println(stu2);*/
//多个对象的读取
Object obj=null;
while((obj=ois.readObject())!=null){
System.out.println(obj);
if(obj instanceof Student){
Student stu3=(Student)obj;
System.out.println(stu3.age+"==="+stu3.name);
}
}
}
}
//序列化就是实现Serializable 接口 然后添加版本号
class Student implements Serializable{
//给对象打上一个serialVersionUID标签 唯一性
private static final long serialVersionUID = 1L;//给该类对象添加版本号
String name;
int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return “Student [name=” + name + “, age=” + age + “]”;
}
}