java 序列化和反序列化 对象流

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/*
 * 对象流
 * ObjectInputStream
 * ObjectOutputStream
 * 1 先写入后读取
 * 2 读取和写入顺序一致
 * 3 不是所有的对象都可以序列化 要支持Serializable
 * 
 * 
 */
public class TestIo14 {
	public static void main(String[] args) throws IOException, ClassNotFoundException {
		//写入
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(baos));
		oos.writeInt(1);
		oos.writeBoolean(false);
		oos.writeObject(new People(11,"dan"));//序列化对象
		oos.flush();
	
		byte[] datas = baos.toByteArray();
		//读取
		ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(new ByteArrayInputStream(datas)));
		int num = ois.readInt();
		boolean chocie = ois.readBoolean();
		Object p = ois.readObject();//反序列化对象
		System.out.println(num);
		System.out.println(chocie);
		
		if (p instanceof People) {//手动类型强转,
			People people = (People) p;
			System.out.println(people.getName() + "\t" + people.getAge());
		}
	}
}


class People implements java.io.Serializable{//继承Serializable 不继承会出现异常
	private transient int age;//transient的意思透明,加上后不会显示响应的属性
	private String name;
	
	public People() {
		// TODO Auto-generated constructor stub
	}

	public People(int age, String name) {
		super();
		this.age = age;
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值