1. Overview
Java中的序列化就是將Java對象的狀態轉化為字節序列,以便存儲和傳輸的機制,在未來的某個時間,可以通過字節序列重新構造對象。把Java對象轉 換為字節序列的過程稱為對象的序列化。把字節序列恢復為Java對象的過程稱為對象的反序列化。這一切都歸功于java.io包下的 ObjectInputStream和ObjectOutputStream這兩個類。
2. Serializable
要想實現序列化,類必須實現Serializable接口,這是一個標記接口,沒有定義任何方法。如果一個類實現了Serializable接口,那么一旦這個類發布,“改變這個類的實現”的靈活性將大大降低。以下是一個序列化的小例子:
class Message implements Serializable{
private static final long serialVersionUID = 1L;
private String id;
private String content;
public Message(String id, String content){
this.id = id;
this.content = content;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String toString(){
return "id = " + id + " content = " + content;
}
}
public class Test{
public static void main(String[] args) {
serialize();
deserialize();
}
private static void serialize(){
Message message = new Message("1", "serializable test");
try {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("Message"));
oos.writeObject(message);
oos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("over");
}
private static void deserialize(){
try {
商賬追收 ObjectInputStream ois = new ObjectInputStream(new FileInputStream("Message"));
Message message = (Message)ois.readObject();
System.out.println(message.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
posted on 2011-06-02 11:38
墻頭草 閱讀(232)
評論(0) 編輯 收藏