Java序列化與反序列化

基礎知識:

1.Java序列化是將對象轉換成字節序列的過程;反之,反序列化就是將字節序列轉換成原來的類對象的過程。

2.判斷Java類對象是否可序列化,只需判斷需序列化的類是否階成了java接口java.io.Serializable,只有當類繼承了該接口,該類的對象纔可被序列化。

3.序列化中使用的API:java.io.ObjectOutputStream和java.io.ObjectInputStream。


序列化和反序列化實例:

Employee類,用於實例化將被序列化的對象

package com.anson.java;

/**
 * Employee類使用
 * @author anson
 *
 */
public class Employee implements java.io.Serializable {

	private String Name;
	private int Age;
	private String Address;
	
	public Employee()
	{
		
	}
	/**
	 * 構造
	 * @param Name
	 * @param Age
	 * @param Address
	 */
	public Employee(String Name,int Age,String Address)
	{
		this.Name=Name;
		this.Age=Age;
		this.Address=Address;
	}
	
	/**
	 * 輸出參數
	 * @return
	 */
	public String Name()
	{
		return this.Name;
	}
	
	public int Age()
	{
		return this.Age;
	}
	
	public String Address()
	{
		return this.Address;
	}
	
}

SerObj類是靜態內部類,用於測試序列化及反序列化

package com.anson.java;
import java.io.*;
import java.util.Vector;

/**
 * 序列化Employee對象
 * @author anson
 *
 */
public  class SerObj {

	/**
	 * 序列化
	 * @param obj
	 * @param path
	 */
	public static void SerObject(Object obj,String path)
	{
		try
		{
			File file=new File(path);
			FileOutputStream outStream=new FileOutputStream(file);
			ObjectOutputStream ObjStream = new ObjectOutputStream(outStream);
			
			for(int i=0;i<10;i++)
			{
				Employee e=new Employee("Name"+i,10+i,"Address"+i);
				ObjStream.writeObject(e);
			}
			
			
			ObjStream.close();
			outStream.close();
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}
	
	/**
	 * 反序列化
	 * @param path
	 */
	public static void UnSerObject(String path)
	{
		try
		{
			File file = new File(path);
			FileInputStream InputStream=new FileInputStream(file);
			ObjectInputStream ObjStream=new ObjectInputStream(InputStream);
			
			Vector<Employee> vec=new Vector<Employee>();
			for(int i=0;i<10;i++)
			{
				vec.add((Employee)ObjStream.readObject());
				
			}
		
			ObjStream.close();
			InputStream.close();
			
			for(int i=0;i<vec.size();i++)
			{
				System.out.print(vec.get(i).Name()+"		");
				System.out.print(vec.get(i).Age()+"		");
				System.out.println(vec.get(i).Address());
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}
}

Test類

package com.anson.java;

/**
 * java序列化測試
 * @author anson
 *
 */
public class Test {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		SerObj.SerObject(null, "/home/anson/桌面/Infor.ser");
		SerObj.UnSerObject("/home/anson/桌面/Infor.ser");
	}

}

測試結果:

運行後將生成文件,用於保存被序列化的對象,獨處文件部分結果如下


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