java IO的基本类ObjectInputStream、ObjectOutputStream(七)


简介

序列化具有持久性的特点,什么时候使用都是可以的,
使用这个对象进行序列化的时候就必须是对象能实现java.io.Serializable接口的实现,虽然里面没有要求实现的方法,但是他是虚拟机是被的标识
a instanceof b 查看a是否是b的实例化
transient 透明化,序列化后,进行反序列化的时候是无法读取他的数据的,针对序列化而言

代码展示

先定义一个类用于实现我们java.io.Serializable的接口,只有实现这个接口我们才可以使用序列化和反序话,这个接口不用实现函数

class emplay2 implements java.io.Serializable{
	private transient String name;
	private int salaty;
	public emplay2(String name, int salaty) {
		super();
		this.name = name;
		this.salaty = salaty;
	}
	public emplay2() {
		super();
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getSalaty() {
		return salaty;
	}
	public void setSalaty(int salaty) {
		this.salaty = salaty;
	}
}

我们进行展示这个类的使用代码

public class file6 {
	public static void file1() throws IOException, ClassNotFoundException{
		//写入一个流:序列化
		BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("obj.txt"));
		ObjectOutputStream dos = new ObjectOutputStream(bos) ;
		dos.writeChar('c');
		dos.writeDouble(3.12);
		dos.writeBoolean(false);
		dos.writeUTF("这个类猛如狗");
		Date da = new Date();
		dos.writeObject(da);
		emplay2 ee = new emplay2("wang",1000);
		dos.writeObject(ee);//必须实现这个接口才可以java.io.Serializable
		dos.flush();
		dos.close();
		
		//输入到系统输出:反序列化
		ObjectInputStream dis = new ObjectInputStream(new BufferedInputStream(new FileInputStream("obj.txt")));
		char c = dis.readChar();
		Double d = dis.readDouble();
		Boolean b1 = dis.readBoolean();
		String s = dis.readUTF();
		System.out.println(c );
		System.out.println(d );
		System.out.println(b1+s );
		Date dd = (Date) dis.readObject();
		System.out.println(dd);
		emplay2 em = (emplay2) dis.readObject();
		System.out.println(em.getName()+""+em.getSalaty());
		dis.close();
	}
	public static void main(String[] args) throws ClassNotFoundException, IOException {
		file1();
	}
}


源码

Github

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值