物件序列化簡單來說就是將物件變成資料流,可以將物件儲存成檔案,可以永久儲存在硬碟中,而且可以在2台電腦之間傳遞物件,是非常實用的功能。
物件反序列化就是將檔案還原成物件,並拿來使用。

重點 : 要被虛列化的物件必須加入Serializable介面,如果該類別也使用到其他類別的物件,那麼其他類別也必須使用Serializable介面,否則執行時期會發生錯誤。

如果序列化的檔案室在A資料夾底下,A資料夾必須先行建立好,否則會一直卡住...程式不會停...。

import
java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
 
public class SerializationDemo {
 
    public static void main(String args[]) {
        //Object serialization 物件序列化
        try {
            MyClass object1 = new MyClass("Hello", 32139604, 2.7e10);
            System.out.println("物件1: " + object1);
            FileOutputStream fos = new FileOutputStream("C:/Cat");
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(object1);
            oos.flush();
            oos.close();
        } catch (Exception e) {
        }
        //Object deserialization 物件反序列化
        try {
            MyClass object2;
            FileInputStream fis = new FileInputStream("C:/Cat");
            ObjectInputStream ois = new ObjectInputStream(fis);
            object2 = (MyClass) ois.readObject();
            ois.close();
            System.out.println("物件2: " + object2);
        } catch (Exception e) {
        }
    }
}
 
 
 
import java.io.Serializable;
 
class MyClass implements Serializable {
 
    String s;
    int i;
    double d;
 
    public MyClass(String s, int i, double d) {
        this.s = s;
        this.i = i;
        this.d = d;
    }
 
    @Override
    public String toString() {
        return "s=" + s + ";   i=" + i + ";   d=" + d;
    }
}


 輸出結果 : (將MyClass儲存成Cat檔案)

物件1: s=Hello; i=32139604; d=2.7E10
物件2: s=Hello; i=32139604; d=2.7E10

arrow
arrow
    全站熱搜

    黃彥霖 發表在 痞客邦 留言(3) 人氣()