Java对象序列化

本文介绍了一个Java程序中实现对象序列化和反序列化的具体例子。通过定义一个包含多个属性的`Person`类,并使用`ObjectOutputStream`和`ObjectInputStream`来完成对象的序列化和反序列化过程。特别地,该示例展示了如何选择性地序列化类的某些属性,同时忽略其他属性。

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

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

class Person implements Serializable
{
	private static final long serialVersionUID = -3569622348945012472L;

	private String name; // 设置transient,name不会被序列化

	private int age;
	
	private transient String sex;
	
	private String type = "美国";


	public Person(String name, int age, String sex, String type){
		this.name = name;
		this.age = age;
		this.sex = sex;
		this.type = type;
	}

	public String toString()
	{
		return "  姓名:" + this.name + 
			   ";年龄:" + this.age + 
			   ";性别:" + this.sex +
			   ";国家:" + this.type;
	}
}


public class Test
{
	public static void main(String[] args) throws Exception
	{
		ser();
		dser();
	}

	public static void ser() throws Exception
	{
		File f = new File("E:" + File.separator + "ss.txt");
		
		OutputStream out = new FileOutputStream(f);
		ObjectOutputStream oos = new ObjectOutputStream(out);
		
		Person per1[][] = {{new Person("张一", 30, "男", "美国"),
							new Person("张二", 31, "女", "美国"),
							new Person("张三", 32, "男", "俄罗斯")},
							{new Person("王一", 40, "男", "美国"),
							new Person("王二", 41, "男", "美国"),
							new Person("王五", 42, "女", "俄罗斯")}};
		
		oos.writeObject(per1);
		
		oos.flush();
		oos.close();
		out.close();
	}

	public static void dser() throws Exception
	{
		File f = new File("E:" + File.separator + "ss.txt");
		
		InputStream ipt = new FileInputStream(f);
		ObjectInputStream ois = new ObjectInputStream(ipt);
		
		Object ps = ois.readObject();
		if(ps != null)
		{
			for(Object o : (Object[][])ps)
			{
				for(Object p : (Object[])o)
				{
					System.out.print(p);
				}
				System.out.println();
			}
		}
		
		ois.close();
		ipt.close();
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值