java——序列化与反序列化

本文介绍Java中如何使用ObjectOutputStream进行对象序列化,将对象状态保存到文件,并通过ObjectInputStream完成对象的反序列化。展示了序列化的基本过程及注意事项。

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

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class ObjectStreamDemo {
	public static void main(String[] args) {
		/**
		 * 对象流
		 * ObjectOutputStream和ObjectInputStream类用于存储和读取基本类型数据或
		 * 对象的过滤流,他可以把java中的对象写到数据源中,也能把对象从数据源中还原回来。
		 * 用ObjectOutputStream类读取基本数据类型或对象的机制叫做序列化;ObjectInputStream
		 * 类读取数据类型或对象的机制叫做反序列化。ObjectOutputStream和ObjectInputStream不能序列化static和
		 * transient修饰的成员变量。
		 * 另外,能被序列化的对象所对应的类必须实现java.io.Serializable这个标志性接口。
		 */
		new ObjectStreamDemo().serializationTest("e:/pratice.html");
		new ObjectStreamDemo().deserializationTest("e:/pratice.html");
		/**
		 * 显式地定义serialVersionUID有一下两种用途:
		 * 1.在某些场合,希望类的不同版本对序列化兼容,因此需要确保类的不同版本具有相同的serialVersionUID.
		 * 2.在某些场合,不希望类的不同版本对序列化兼容,因此需要确保类的不同版本具有不同的serialVersionUID.
		 */
	}
	
	private void serializationTest(String filepath){
		ObjectOutputStream oos = null;
		try {
			oos = new ObjectOutputStream(new FileOutputStream(filepath));
			oos.writeObject(new Student(1, "xiex", 18));
			oos.flush();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			if(oos != null){
				try {
					oos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	private void deserializationTest(String filepath){
		try {
			ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filepath));
			Student stu = (Student) ois.readObject();
			System.out.println(stu);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		
		
	}
}

class Student implements Serializable{

	private static final long serialVersionUID = 1L;
	
	private int id;
	private String name;
	private transient int age;
	@Override
	public String toString() {
		return "Student [id=" + id + ", name=" + name + ", age=" + age + "]";
	}
	public Student(int id, String name, int age) {
		super();
		this.id = id;
		this.name = name;
		this.age = age;
	}
	public Student() {
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	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;
	}
	
	
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值