對象的序列化與反序列化

對象的序列化與反序列

package cn.et.five;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class Test {
	
	//將對象序列化爲字節數組
	public static byte[] ser(Object obj) throws IOException{
		//接收被寫入的字節數組
		ByteArrayOutputStream bos= new ByteArrayOutputStream();
		//把對象序列化成字節數組
		ObjectOutputStream oos= new ObjectOutputStream(bos);
		//寫入
		oos.writeObject(obj);
		return bos.toByteArray();
	}
	
	//反序列化		
	public static Object dser(byte[] src) throws Exception{
		//從字節數組讀取數據
		ByteArrayInputStream bis = new ByteArrayInputStream(src);
		//把字節數組反序列化成對象
		ObjectInputStream ois= new ObjectInputStream(bis);
		return ois.readObject();	
	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章