序列化是将对象的状态写入到特定的流中的过程
反序列化则是从特定的流中获取数据重新构建对象的过程
对象输出流ObjectOutputStream
结合FileOutputStream使用,实现对象的序列化
writerObject(Object)
对象输入流ObjectInputStream
结合FileInputStream使用,实现对象的反序列化
Object readObject()
对象类型必须实现Serializable接口
创建学员类型
public class Student implements Serializable {
private int id;
private int age;
private String name;
private double height;
public Student(){
}
public Student(int age, String name) {
this.age = age;
this.name = name;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", age=" + age +
", name='" + name + '\'' +
", height=" + height +
'}';
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
}
序列化和反序列化学员对象
public class TestOBJ {
public static void main(String[] args) throws Exception{
Student s= new Student();
s.setId(6);
s.setName("穷穷");
s.setAge(18);
s.setHeight(120);
System.out.println(s);
FileOutputStream fos=new FileOutputStream("d.txt");
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(s);
FileInputStream fis=new FileInputStream("d.txt");
ObjectInputStream ois=new ObjectInputStream(fis);
Object o=ois.readObject();
System.out.println(o);
if (o instanceof Student){
Student stu=(Student) o;
System.out.println(stu.getName());
}
ois.close();
fis.close();
oos.close();
fos.close();
}
}
本文介绍了Java中的对象序列化与反序列化,通过`ObjectOutputStream`和`ObjectInputStream`实现对象的持久化存储。示例展示了如何创建一个`Student`类并实现序列化,以及如何进行序列化和反序列化操作。在反序列化时,需要注意对象必须实现`Serializable`接口。
4083

被折叠的 条评论
为什么被折叠?



