JAVA基礎之序列化與還原序列化

來源:互聯網
上載者:User

標籤:obj   基礎   轉化   port   system   一個   nts   blog   返回   

序列化和還原序列化:

  把對象轉化為位元組序列的過程稱為序列化;

  把位元組序列恢複為對象的過程稱為對象的還原序列化;

方法:

  Java.io.ObjectOutputStream代表對象的輸出資料流,writeObject(Object obj)方法對參數對象進行序列化,把得到的位元組序列寫到一個目標輸出資料流中。

  Java.io.ObjectInputStream代表對象的輸入資料流,readObject()方法可以從一個源輸入資料流中讀取位元組序列,並轉化為一個對象,將其返回。

  只有實現Serializable和Externalizable介面的類的對象才能被序列化。

  Externalizable介面繼承自 Serializable介面,實現Externalizable介面的類完全由自身來控制序列化的行為,而僅實現Serializable介面的類可以 採用預設的序列化方式 。
  對象序列化包括如下步驟:
  1) 建立一個對象輸出資料流,它可以封裝一個其他類型的目標輸出資料流,如檔案輸出資料流;
  2) 通過對象輸出資料流的writeObject()方法寫對象。
  對象還原序列化的步驟如下:
  1) 建立一個對象輸入資料流,它可以封裝一個其他類型的源輸入資料流,如檔案輸入資料流;
  2) 通過對象輸入資料流的readObject()方法讀取對象。

執行個體:

 1 import java.io.File; 2 import java.io.FileInputStream; 3 import java.io.FileNotFoundException; 4 import java.io.FileOutputStream; 5 import java.io.IOException; 6 import java.io.ObjectInputStream; 7 import java.io.ObjectOutputStream; 8 import java.io.Serializable; 9 import java.text.MessageFormat;10 11 12 class Person implements Serializable{13     private int age;14     public int getAge() {15         return age;16     }17     public void setAge(int age) {18         this.age = age;19     }20     public String getName() {21         return name;22     }23     public void setName(String name) {24         this.name = name;25     }26     private String name;27 }28 public class test {29     public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException30     {31         SerialiablePerson();32         Person p=DeserializePerson();33          System.out.println(MessageFormat.format("name={0},age={1}",p.getName(),p.getAge()));    34     }
      //還原序列化的過程,從位元組序列檔案讀出並返回
35 public static Person DeserializePerson() throws FileNotFoundException, IOException, ClassNotFoundException{36 ObjectInputStream in=new ObjectInputStream(new FileInputStream(new File("E://person.txt")));37 Person p=(Person)in.readObject();38 return p;39 }
     //序列化的過程,將位元組存到E://Person.txt中
40 public static void SerialiablePerson() throws FileNotFoundException, IOException {41 Person p=new Person();42 p.setAge(15);43 p.setName("姓氏");44 45 ObjectOutputStream out=new ObjectOutputStream(new FileOutputStream(new File("E://Person.txt")));46 out.writeObject(p);47 out.close();48 }49 50 }

 

JAVA基礎之序列化與還原序列化

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.