ObjectInputStream 与 ObjectOutputStream

ObjectInputStream 与 ObjectOutputStream

序列化与反序列化
ObjectInputStream -------- ObjectOutputStream
| |
| |
反序列化 序列化
|----------------------------|----------------------------|
| |-------------- | |
| Serialization |----->FILE |-----| Deserialization |
| | | | | | |
| Object—Stream Of bytes—| -------DB |-----------Stream Of bytes -------Object |
| (输出流) || || || (输入流) ||
| |-----MEMORY|-----| |
| |

 不是所有对象都可以序列化  必须实现java.io.Serializable接口才能实现序列化 写入到流中

package com.sxt.io;

import java.io.*;
import java.net.URL;
import java.util.Date;

/**
*

  • @author YF
  • ObjectInputStream and ObjectOutputStream
  • <dis : 不是所有的对象都可以做直接实现序列化 必须实现java.io.Serializable接口才能实现序列化 写入到流中>
    */

public class FileDemo01 {
public static void main(String []args) throws IOException, ClassNotFoundException {//抛出异常
ByteArrayOutputStream s = new ByteArrayOutputStream();
ObjectOutputStream I = new ObjectOutputStream(new BufferedOutputStream(s));//<序列化>
//操作数据类型 与 数据

	I.writeObject("核心");
	I.writeObject(18);
	I.writeObject(new Date());
	Cs g = new Cs("xiaotian","lihua",20); 
	I.writeObject(g);
	I.flush();
    I.close();
	byte[] buff = s.toByteArray();
	ObjectInputStream p = new ObjectInputStream(new BufferedInputStream(new ByteArrayInputStream(buff)));//<反序列化>
	//读写数据
	Object sr = p.readObject();
	Object i = p.readObject();
	Object D = p.readObject();
	Object CS = p.readObject();
	//通过判断 来if分别还原数据  写的比较简单   有改进空间
	if(sr instanceof String) {
		String srobj = (String)sr;
		System.out.println(sr);
	}
	if(i instanceof Integer) {
		int iobj = (int)i;
		System.out.println(i);
	}
	if(D instanceof Date) {
		Date Dobj = (Date)D;
		System.out.println(D);
	}
	if(CS instanceof Cs) {
		Cs CSobj = (Cs)CS;
		System.out.println(CS);
	}
	// 将数据存储起来   称为  持久化
	p.close();
}

}

//javabean 封装数据
class Cs implements java.io.Serializable{ //引用接口 使其序列化
private String staff;
private String groupLeader;
private transient int numberOfPeople;// transient 透明 可以让该数据不会被序列化
public Cs(){}
public Cs(String staff,String groupLeader,int numberOfPeople) {
this.staff = staff;
this.numberOfPeople = numberOfPeople;
this.groupLeader = groupLeader;
}
public String getStaff() {
return staff;
}
public int getnumberOfPenple() {
return numberOfPeople;
}
public String getGroupLeader() {
return groupLeader;
}
public void setStaff(String staff) {
this.staff = staff;
}
public void setnumberOfPenple(int numberOfPeople) {
this.numberOfPeople = numberOfPeople;
}
public void setGroupLeader(String groupLeader) {
this.groupLeader = groupLeader;
}
public String toString() {
return groupLeader +" “+ numberOfPeople+” "+ staff;
}
}

上一篇:Opencv 图像处理-Contours函数提取轮廓及感兴趣区域ROI的必用且实用操作技巧-(涵盖Contours的一切使用基础,附代码段)


下一篇:ObjectInputStream对象流