序列化

本文介绍了一个Java程序中如何实现对象的序列化与反序列化过程,包括创建可序列化的Student类实例,将其写入文件,再从文件中读取并还原为对象的具体步骤。

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

序列化学习
//前提是Student类已经实现Serializable接口
//这是前提,然后再进行序列化和反序列
package IO;
import java.io.*;
public class Usestudent {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
Student stu=new Student("TOM",'M',20,3.6);
File f=new File("D:"+File.separator+"hello3.txt");
//序列化到文件里面,所以必须先创建一个file
try
{
	f.createNewFile();
}
catch(IOException e)
{
	e.printStackTrace();
}
//序列化
try {
	FileOutputStream out=new FileOutputStream(f);//1、文件流
	ObjectOutputStream ob1=new ObjectOutputStream(out);//序列流
	ob1.writeObject(stu);//目标对象写入
	out.close();
	ob1.close();
//反序列化
	FileInputStream in=new FileInputStream(f);
	ObjectInputStream ob2=new ObjectInputStream(in);
    Student st1=(Student)ob2.readObject();//将字节序列返回成student对象
    System.out.println("name = " + st1.getName());  
    System.out.println("sex = " + st1.getSex());  
    System.out.println("year = " + st1.getYear());  
    System.out.println("gpa = " + st1.getGpa());  
	in.close();
	ob2.close();
	
} catch (FileNotFoundException e) {
	// TODO Auto-generated catch block
	e.printStackTrace();
}
catch (IOException e)  
{  
 e.printStackTrace();  
	} catch (ClassNotFoundException e) {
	// TODO Auto-generated catch block
	e.printStackTrace();
}

}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值