1. 程式人生 > >探究JAVA序列化與反序列化

探究JAVA序列化與反序列化

探究JAVA序列化與反序列化

 序列化JavaBean物件

public class User implements Serializable {
	/**
		 * 序列化User
		 * 
		 * 繼承Serializable介面
		 * 新增序列化ID
		 */
	private static final long serialVersionUID = 5451342742084459797L;
	private Integer user_id;
	private String user_name;
	private String user_password;
	private String user_img;
	private Integer user_value;
	private Date user_punch;
	private List<Code> code_id;

}

 

序列化User

	/**
	 * 序列化
	 * 
	 * @param fileName
	 * @param o
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	public void serialize(String fileName, Object o) throws FileNotFoundException, IOException {
		//利用ObjectOutputStream()方法建立User的序列化檔案的輸出流
		ObjectOutputStream us = new ObjectOutputStream(new FileOutputStream(fileName));
		//呼叫writeObject()將User物件寫入序列化檔案
		us.writeObject(o);
		//關閉輸出流
		us.close();
	}	

        反序列化User

/**
	 * 反序列化
	 * 
	 * @param cls
	 * @param fileName
	 * @return
	 * @throws ClassNotFoundException
	 * @throws IOException
	 */
	public <T> T unSerialize(Class<T> cls, String fileName) throws ClassNotFoundException, IOException {
		//利用ObjectOutputStream()方法獲取序列化檔案的輸入流
		ObjectInputStream fi = new ObjectInputStream(new FileInputStream(fileName));
		//呼叫readObject()將檔案反序列為User物件
		T obj = (T) fi.readObject();
		//關閉輸入流
		fi.close();
		//返回User物件
		return obj;
	}