作者:gnuhpc
出處:http://www.cnblogs.com/gnuhpc/
Serializable介面中沒有任何的方法。當一個類聲明要實現Serializable介面時,只是表明該類參加序列化協議,而不需要實現任何特殊的方法。
注意:Thread類不能被並行化
import java.io.Serializable;
public class Goober implements Serializable {
private int width;
private String color;
private transient long work;//若你的類中有不能並行化的或者不想並行化的成員,則使用transient進行忽略
Goober() {
width = 99;
color = "puce";
}
void setColor(String setting) {
color = setting;
}
String getColor() {
return(color);
}
}
========寫=======
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.IOException;
public class SerialDemo1 {
public static void main(String arg[]) {
Goober goober = new Goober();
goober.setColor("magenta");
try {
FileOutputStream fos = new FileOutputStream("sergoob");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(goober);
oos.close();
} catch(IOException e) {
System.out.println(e);
}
}
}
========讀=======
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
public class SerialDemo2 {
public static void main(String arg[]) {
Goober goober = null;
try {
FileInputStream fis = new FileInputStream("sergoob");
ObjectInputStream ois = new ObjectInputStream(fis);
goober = (Goober)ois.readObject();
ois.close();
} catch(IOException e) {
System.out.println(e);
} catch(ClassNotFoundException e) {
System.out.println(e);
}
String color = goober.getColor();
System.out.println(color);
}
}
注意:
1.Demo1和Demo2都要求有Goober這個類,也就是說,實質上,方法本身並沒有因為序列化而儲存在檔案中。
2.真正的對象持久化建議使用關係型資料庫或者XML檔案,通用性較高,而序列化要求雙方都是Java才可以。
作者:gnuhpc
出處:http://www.cnblogs.com/gnuhpc/