要实例化的类要实现Serializable接口
类
public class Student implements Serializable{
/**
*
*/
private static final long serialVersionUID =
-1963583189713190333L;
private String name;
private int age;
public Student(String name, int age) {
super();
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 Test01 {
public static void main(String[] args) throws Exception {
FileOutputStream fileOutputStream = new
FileOutputStream("F:\\abc\\a.txt");
ObjectOutputStream objectOutputStream =
new ObjectOutputStream(fileOutputStream);
Student student = new Student("lbc", 18);
objectOutputStream.writeObject(student);
objectOutputStream.close();
}
得到的结果是这样的

反序列化
将硬盘中的对象读出
public class Test01 {
public static void main(String[] args) throws Exception {
FileInputStream in = new FileInputStream("F:\\\\abc\\\\a.txt");
ObjectInputStream objectInputStream = new ObjectInputStream(in);
Object readObject = objectInputStream.readObject();
System.out.println(readObject);
objectInputStream.close();
}
}
得到的结果

本文介绍Java中如何通过实现Serializable接口完成对象的序列化和反序列化过程。具体包括定义可序列化的Student类,并演示如何将此类实例写入文件及从文件中读取。
&spm=1001.2101.3001.5002&articleId=109580785&d=1&t=3&u=dc5415e3f7784442a470ef970a9f82f0)
609





