java物件序列化和反序列化機制
阿新 • • 發佈:2021-01-17
技術標籤:java
java物件序列化和反序列化機制:
對於物件流來說引出了序列化和反序列化機制
序列化(Serialization)是將物件的狀態資訊轉化為可以儲存或者傳輸的形式的過程,一般將一個物件儲存到一個儲存媒介,例如檔案或記憶體緩衝等,在網路傳輸過程中,可以是位元組或者XML等格式;而位元組或者XML格式的可以還原成完全相等的物件,這個相反的過程又稱為反序列化;
person.java
import java.io.Serializable; public class person implements Serializable { public static final long serialVersionUID = 11111111111111L; private String name; private int age; public person() { } public person(String name, int age) { this.name = name; this.age = age; } 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; } @Override public String toString() { return "person{" + "name='" + name + '\'' + ", age=" + age + '}'; } }
demo09.java
import java04.person; import org.junit.Test; import java.io.*; public class demo09 { @Test public void test1(){ //物件流 //序列化:物件寫入資料來源中 :寫 //反序列化:資料來源-物件 :讀 ObjectOutputStream oos = null; try { oos = new ObjectOutputStream(new FileOutputStream("object.dat")); oos.writeObject(new String("我愛北京天安門")); oos.flush(); oos.writeObject(new person("李四",11)); oos.flush(); } catch (IOException e) { e.printStackTrace(); } finally { if(oos != null){ try { oos.close(); } catch (IOException e) { e.printStackTrace(); } } } } @Test public void test2(){ ObjectInputStream ois = null; try { ois = new ObjectInputStream(new FileInputStream("object.dat")); Object obj = ois.readObject(); String str = (String)obj; System.out.println(str); person p = (person)ois.readObject(); System.out.println(p); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { if(ois!=null){ try { ois.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
結果:
序列化的條件:
1.implement Servialization
2.有一個serialVersionUID
3.除了Person實現介面外,還保證屬性也實現介面