Java对象数组序列化与反序列化

先创建一个Java Bean
/**一个low的Java Bean*/
public class Box implements Serializable{
	private int width;
	private int height;
	
	public Box(){
		
	}
	
	public Box(int width,int height){
		this.width = width;
		this.height = height;
	}
	
	public void setWidth(int width){
		this.width = width;
	}
	public void setHeight(int height){
		this.height = height;
	} 
	
	public int getWidth(){
		return width;
	}
	
	public int getHeight(){
		return height;
	}
}

一般都是直接把一个对象序列化,如果我们有多个同一个类的对象,那么可以将这多个对象存进一个数组中,这个数组可以时静态数组也可以是动态数组,因为数组本身也是一个对象,将这个数组对象进行序列化,最后反序列化的时候也将得到一个数组对象。
public class SerializaToFlatFile {
	public static void main(String[] args) throws Exception {
		SerializaToFlatFile ser = new SerializaToFlatFile();
		// 将Box对象数组存进动态数组ArrayList中
		ArrayList
     
     
      
       array = new ArrayList
      
      
       
       ();
		Box boxOne = new Box(816, 523);
		Box boxTwo = new Box(823, 324);
		Box boxThree = new Box(111, 222);
		array.add(boxOne);
		array.add(boxTwo);
		array.add(boxThree);
		// 序列化
		ser(array);
		// 反序列化
		array = dSer();
		// 反序列化后的处理
		printObj(array);
	}

	/** 序列化 */
	public static void ser(Object object) throws Exception {
		FileOutputStream fos = new FileOutputStream("foo.ser");
		ObjectOutputStream oos = new ObjectOutputStream(fos);
		oos.writeObject(object);
		oos.flush();
		oos.close();

	}

	/** 反序列化 */
	public static ArrayList
       
       
        
         dSer() throws Exception {
		FileInputStream fis = new FileInputStream("foo.ser");
		ObjectInputStream ois = new ObjectInputStream(fis);
		ArrayList
        
        
         
          array = (ArrayList
         
         
           ) ois.readObject(); return array; } /** 反序列化后的处理 */ public static void printObj(ArrayList 
          
            array) { for (int i = 0; i < array.size(); i++) { System.out.println("width = " + ((Box) array.get(i)).getWidth() + "\r\n" + "height = " + ((Box) array.get(i)).getHeight()); } } } 
           
         
        
        
       
       
      
      
     
     

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值