[java]代码库import java.io.*;
public class SerializableDemo {
public static void main(String args[]) throws IOException,
ClassNotFoundException {
Student stu = new Student(1564163, "xxx", 18, "CSD");
FileOutputStream fo = new FileOutputStream("data.ser");
// 保存对象的状态
ObjectOutputStream so = new ObjectOutputStream(fo);
try {
so.writeObject(stu);
so.close();
} catch (IOException e) {
System.out.println(e);
}
FileInputStream fi = new FileInputStream("data.ser");
ObjectInputStream si = new ObjectInputStream(fi);
// 恢复对象的状态
try {
stu = (Student) si.readObject();
si.close();
} catch (IOException e) {
System.out.println(e);
}
}
}
class Student implements Serializable {
int id; // 学号
String name; // 姓名
int age; // 年龄
String department; // 系别
public Student(int id, String name, int age, String department) {
this.id = id;
this.name = name;
this.age = age;
this.department = department;
}
}

这篇博客介绍了如何使用Java的序列化机制将对象永久保存到硬盘。通过`SerializableDemo`类的实例,展示了如何创建一个`Student`对象,并使用`ObjectOutputStream`将其状态写入文件"data.ser",然后利用`ObjectInputStream`从文件中恢复对象状态。这为Java对象提供了持久化存储的解决方案。

392

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



