java 对象序列化磁盘_java对象序列化 永久保存到硬盘

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

[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;

}

}

694748ed64b9390909c0d88230893790.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值