java序列化对象实例——源于孙鑫老师的java无难事视频教程

本文通过一个Java程序实例介绍了如何使用序列化和反序列化来保存和读取对象状态。程序创建了三个Employee对象,并将它们写入到文件中。随后,程序从该文件中读回这些对象并打印出来。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

class ObjectSerialTest
{
public static void main(String[] args) throws Exception
{
Employee e1=new Employee("zhangsan",25,3000.50);
Employee e2=new Employee("lisi",24,3200.40);
Employee e3=new Employee("wangwu",27,3800.55);

FileOutputStream fos=new FileOutputStream("employee.txt");
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(e1);
oos.writeObject(e2);
oos.writeObject(e3);
oos.close();

FileInputStream fis=new FileInputStream("employee.txt");
ObjectInputStream ois=new ObjectInputStream(fis);
Employee e;
for(int i=0;i<3;i++)
{
e=(Employee)ois.readObject();
System.out.println(e.name+":"+e.age+":"+e.salary);
}
ois.close();
}
}

class Employee implements Serializable
{
String name;
int age;
double salary;
transient Thread t=new Thread();
public Employee(String name,int age,double salary)
{
this.name=name;
this.age=age;
this.salary=salary;
}
private void writeObject(java.io.ObjectOutputStream oos) throws IOException
{
oos.writeInt(age);
oos.writeUTF(name);
System.out.println("Write Object");
}
private void readObject(java.io.ObjectInputStream ois) throws IOException
{
age=ois.readInt();
name=ois.readUTF();
System.out.println("Read Object");
}

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值