你有沒有想過,怎麼把一個物件「打包」存到硬碟裡,之後再原封不動地取出來?序列化機制就是為了解決這個問題而存在的。
序列化(Serialization),說白了就是把物件此刻的狀態轉換成能夠保存或傳輸的格式。在這個過程中,物件會把自己當下的狀態寫進臨時或持久的儲存區;等到需要用的時候,只要從儲存區把資料讀回來做反序列化,就能重建出一個一模一樣的物件。
任何想被序列化的類別,都必須實作 java.io.Serializable 這個標記介面。以下是我們接下來要用的 Person:
package exercise;
import java.io.Serializable;
public class Person implements Serializable{
private String name;
private int age;
public Person() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
}
package exercise;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
public class ObjectStreamDemo1 {
public final static String PATH = "obj.object1";
public static void main(String[] args) throws IOException,
ClassNotFoundException {
//writeObj();
readObj();
System.out.println("--End--");
}
public static void readObj() throws IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(PATH));
Person p = (Person)ois.readObject();
System.out.println(p.getName() + "|" + p.getAge());
}
public static void writeObj() throws IOException {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(PATH));
oos.writeObject(new Person("張三", 30));
oos.close();
}
}
執行後,主控台會印出先前寫入的姓名與年齡,代表還原成功。
實務上更常見的是一次存一整批資料,這時候把集合物件寫進串流即可:
package exercise;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
public class ObjectStreamDemo2 {
public final static String PATH = "obj.object";
public static void main(String[] args) throws IOException,
ClassNotFoundException {
//writeObj();
readObj();
System.out.println("---end!---");
}
public static void readObj() throws IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(PATH));
List<Person> persons = (List<Person>)ois.readObject();
for(Person p:persons){
System.out.println(p.getName() + "|" + p.getAge());
}
}
public static void writeObj() throws IOException {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(PATH));
List<Person> persons = new ArrayList<Person>();
Person p1 = new Person("張三",18);
Person p2 = new Person("李四",19);
persons.add(p1);
persons.add(p2);
oos.writeObject(persons);
oos.close();
}
}
迴圈會依序印出兩筆資料,說明整個 List 都被完整還原。
· 實體類一定要實作 java.io.Serializable,否則會在寫入時丟出例外。
· 輸出的 obj.object 是二進位檔,用記事本開只會看到一堆亂碼,這是正常現象,不是檔案壞了。
序列化在 Web 技術裡扮演的角色相當關鍵,不論是 session 的持久化、快取落地還是 RPC 的資料傳遞,背後幾乎都有它的影子。希望正在學 Java 的朋友能把這個機制真正理解並用起來。
以上內容為個人學習整理,不代表任何團體或單位;若有理解不到位之處,还请多多包涵。