java中序列化一個物件儲存在檔案中的簡單過程
為什麼要序列化?
因為在儲存一個物件或者大型資料型別時,因為平臺的不同(比如作業系統不同),需要通過網路傳遞時,需要適應對方的環境或者網路的協議,要將物件的資料轉化成一種標準的位元組流序列,從而能在其他平臺還原出來和符合網路傳輸的要求。
所有分散式應用常常需要跨平臺,跨網路,因此要求所有傳的引數、返回值都必須實現序列化。
簡單來說:
序列化:把Java物件轉換為位元組序列的過程。
反序列化:把位元組序列恢復為Java物件的過程。
下面寫個簡單的例子:
建立一個Student類,三個成員變數id,name,hobby和一個靜態變數sex,其中hobby前加了不參與序列化關鍵詞transient
一個無參構造方法和一個兩個引數的構造方法,重寫toString,以及若干set,get方法。
public class Student implements Serializable{ private int id;; private String name; public static String sex="女"; public transient String hobby="吃吃吃"; public Student() { this.id=1; } public Student(int id, String name) { super(); this.id = id; this.name = name; this.id=2; } @Override public String toString() { return "Student [id=" + id + ", name=" + name +",sex="+sex+ ",hobby="+hobby+"]"; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getHobby() { return hobby; } public void setHobby(String hobby) { this.hobby = hobby; } }
第一個測試方法:
public class Test { public static void main(String[] args) throws Exception { Student student = new Student(1, "麗日御茶子"); System.out.println(student); student.sex="男"; student.setId(3); student.setHobby("玩玩玩"); FileOutputStream fos=new FileOutputStream("F:"+File.separator+"TestFiles"+File.separator+"MyTest.txt"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(student); System.out.println(student); oos.close(); FileInputStream fis = new FileInputStream("F:"+File.separator+"TestFiles"+File.separator+"MyTest.txt"); ObjectInputStream ois = new ObjectInputStream(fis); Student student2= (Student) ois.readObject(); System.out.println(student2); } }
結果:
Student [id=2, name=麗日御茶子,sex=女,hobby=吃吃吃]
Student [id=3, name=麗日御茶子,sex=男,hobby=玩玩玩]
Student [id=3, name=麗日御茶子,sex=男,hobby=null]
第二個測試:
第一個程式已經執行完,且刪掉前面程式碼,直接讀取
public class Test {
public static void main(String[] args) throws Exception {
FileInputStream fis = new FileInputStream("F:"+File.separator+"TestFiles"+File.separator+"MyTest.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
Student student2= (Student) ois.readObject();
System.out.println(student2);
}
}
結果:
Student [id=3, name=麗日御茶子,sex=女,hobby=null]
第一次測試結果:
從第一個結果來看,第一次列印的是預設例項化後的結果
第二次對變數設定過後的列印也沒有什麼問題
第三次打印發現hobby變成了null
原因:transient修飾過的變數不參與序列化,String預設值是為null,數值則為0
第二次測試結果:
性別變成了女,id還是3,hobby是null
原因:id在序列化前已經被設定成3,序列化後該值被儲存了起來,再次讀取依舊是3,沒有執行構造方法,所以得出反序列化是不會執行構造方法的。
hobby因為是加了transient所以不參與序列化沒有被儲存起來。
sex回到了原來的值女,而在第一次測試裡第三次列印的結果是男,因為第一次測試裡jvm並沒有停止,所以方法區裡sex的值被設定後確實變成了男,而靜態變數是不參與序列化的,所以第一個測試程式裡讀取反序列化物件時,因為都是Student類所以都使用同一個地址上的值,而sex這個地址上的值已經被改變,所以列印的結果也被改變。而第二次測試裡jvm已經重啟,原來方法區裡的sex的地址已經消失,在讀取反序列化物件時又會進行一次類載入,載入時就會按照Student裡寫的static的預設值重新分配地址和預設值,所以讀取的結果就是原來的值了。