JAVA對象序列化(Serializable、ObjectOutputStream、ObjectInputStream、 transient)
阿新 • • 發佈:2017-07-23
nbsp 輸出流 out void hang this 對象 code ransient
1)對象序列化是把一個對象變為二進制的數據流的一種方法。對象序列化後可以方便的實現對象的傳輸或存儲。
2)如果一個類的對象想被序列化,則對象所在的類必須實現Serialilzable接口。此接口中沒有定義任何方法,所以此借口是一個標識接口,表示一個類具備被序列化的能力。
3)對象被序列化後變為二進制,可以經過二進制數據流進行傳輸。此時必須依靠對象輸出流(ObjectOutputStream)和對象輸入流(ObjectInputStream)。
4)在序列化中,只有屬性被序列化。因為每個對象都具有相同的方法,但是每個對象的屬性是不相同的,也就是說,對象保存的只有屬性信息,所以在序列化時,只有屬性被序列化。
1 public class Person implements Serializable { 2 private String name; 3 private int age; 4 public Person(String name,int age){ 5 this.name = name; 6 this.age = age; 7 } 8 public String toString(){ 9 return this.name + "....." + this.age; 10 }11 }
1 import java.io.File; 2 import java.io.FileNotFoundException; 3 import java.io.FileOutputStream; 4 import java.io.IOException; 5 import java.io.ObjectOutputStream; 6 import java.io.OutputStream; 7 8 public class SerDemo01 { 9 10 public static void main(String[] args) throws Exception {11 File f = new File("D:" + File.separator + "test.txt"); 12 ObjectOutputStream oos = null; 13 OutputStream out = new FileOutputStream(f); 14 oos = new ObjectOutputStream(out); 15 oos.writeObject(new Person("zhangsan",30)); 16 oos.close(); 17 } 18 19 }
1 import java.io.File; 2 import java.io.FileInputStream; 3 import java.io.InputStream; 4 import java.io.ObjectInputStream; 5 6 public class SerDemo02 { 7 8 public static void main(String[] args) throws Exception{ 9 File f = new File("D:" + File.separator + "test.txt"); 10 ObjectInputStream ois = null; 11 InputStream input = new FileInputStream(f); 12 ois = new ObjectInputStream(input); 13 Object obj = ois.readObject(); 14 ois.close(); 15 System.out.println(obj); 16 } 17 18 }
輸出結果為:張三.....30
如果一個對象的某些屬性不希望被序列化,則可以使用transient關鍵字進行聲明,
如果將上述Person類中的private String name;修改為private transient String name;
最後輸出的結果為:null.....30
JAVA對象序列化(Serializable、ObjectOutputStream、ObjectInputStream、 transient)