ObjectStream

2 篇文章 0 订阅

例:将Employee对象及数组对象存储在文件中,再读出. 其中age属性不需要序列化

/*
 * 需要序列化的对象必须实现Serializable接口(空接口)
 * 若其中存在不想序列化的属性,加transient关键字
 */
public class Employee implements Serializable{
	private String name;
	private transient int age;   //不将age属性序列化
	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;
	}
	public Employee(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}
}
/*
	 * 若存储多个对象,只需多次调用writeObject()和readObject()方法
	 * 对象按顺序写入和读取
	 */
	@Test
	public void test1() throws FileNotFoundException, IOException, ClassNotFoundException {
		
		Employee e=new Employee("小红", 13);
		File src=new File("io.txt");
		
		//序列化, 将对象存储在文件中
		ObjectOutputStream oos=new ObjectOutputStream(
				new BufferedOutputStream(new FileOutputStream(src)));
		oos.writeObject(e);
		
		//存储一个数组
		int[]  i= {1,2,3,4,5};
		oos.writeObject(i);
		
		oos.flush();
		oos.close();
		
		//反序列化.从文件中读出对象
		ObjectInputStream ois=new ObjectInputStream(
				new BufferedInputStream(new FileInputStream(src)));
		e=(Employee)ois.readObject();
		System.out.println(e.getAge());     //age属性打印出来为0,因为加了transient关键字
		System.out.println(e.getName());
		
		//从文件中读取数组
		i=(int[])ois.readObject();
		System.out.println(Arrays.toString(i));
		
	}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值