IO_对象流

与数据流相同:处理基本数据类型和字符串
与数据流不同:处理其他各种对象(包括)
特殊概念: 序列化和反序列化原则:
1、先写出后读取
2、读取的顺序和写出的一致
3、不是所有的对象都可以序列化
自定义的对象需要序列化需要实现Serialization接口(虚拟机识别的“通行证”)

ObjectOutputStream: Object -(输出)-> Stream of byte(Serialization序列化) -(存储)-> file/DB/memory
ObjectInputStream: Object <-(输入)- Stream of byte(Deserialization反序列化) <-- file/DB/memory

在这里插入图片描述

voidwriteObject(Object obj)将指定的对象写入 ObjectOutputStream
ObjectreadObject()从 ObjectInputStream 读取对象

测试代码:

public class ObjectTest {
	public static void main(String[] args) throws IOException, ClassNotFoundException {
//		①写出
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(baos));
//		操作数据类型+数据
		oos.writeUTF("凡是过往");
		oos.writeInt(18);
		oos.writeChar('a');
		oos.writeBoolean(false);
//		对象(字符串、日期、自定义的对象(手动实现序列化))
		oos.writeObject("皆为序列");/*字符串实现了序列化:public class String implements java.io.Serializable*/
		oos.writeObject(new Date());/*日期实现了序列化:public class Date implements java.io.Serializable*/
		Employee emp = new Employee("John",1024);/*Employee手动实现了序列化:class Employee implements java.io.Serializable*/
		oos.writeObject(emp);
		oos.flush();
		byte[] datas = baos.toByteArray();
		System.out.println(datas.length);
//		②读取
		ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(new ByteArrayInputStream(datas)));
		String msg = ois.readUTF();
		int age = ois.readInt();
		char grade = ois.readChar();
		boolean flag = ois.readBoolean();
		Object str = ois.readObject();
		Object date = ois.readObject();
		Object emploee = ois.readObject();
//		把各种类型的转化成字符串instanceof
		/*是String实例,则将其转化成字符串*/
		if(str instanceof String) {
			String strObj = (String)str;
			System.out.println(strObj);
		}
		if(date instanceof Date) {
			Date dateObj = (Date)date;
			System.out.println(dateObj);
		}
		if(emploee instanceof Employee) {
			Employee emploeeObj = (Employee)emploee;
			System.out.println(emploeeObj.getName() + "-->" + emploeeObj.getSalary());
		}
	}
}

//Javabean用于封装数据
class Employee implements java.io.Serializable{
	private String name;
	private double salary;
	public Employee() {
	}
	public Employee(String name, double salary) {
		super();
		this.name = name;
		this.salary = salary;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public double getSalary() {
		return salary;
	}
	public void setSalary(double salary) {
		this.salary = salary;
	}
}

测试结果:

172
皆为序列
Thu Sep 05 17:19:13 CST 2019
John-->1024.0

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值