序列化和反序列化、 对象的序列化流

序列化和反序列化

  图解:

    

 

 对象的序列化流

  ObjectOutputStream:对象的序列化

  作用:

    把对象以流的方式写入到文件中

 构造方法:

    ObjectOutputStream(OutputStream  out)创建写人指定 ObjectOutputStream 的 ObjectOutputStream

  参数:

    OutputStream  out:字节输出流

   特有的成员方法:

    void writerObject(Object o)将指定的对象写入 ObjectOutputStream

  案例:

    

public class Student implements Serializable {
String name;
int age;

public Student(String name, int age) {
this.name = name;
this.age = age;
}

public Student() {

}

@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", 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 Xujie {
public static void main(String[] args) throws IOException {
Student student = new Student("大傻",13);
ObjectOutputStream stream = new ObjectOutputStream(new FileOutputStream("aa.txt"));
stream.writeObject(student.toString());
stream.flush();
stream.close();
}
}

看运行结果:

  

 

 

  

posted @ 2022-07-21 10:19  一位程序袁  阅读(27)  评论(0编辑  收藏  举报