JAVA類的序列化

來源:互聯網
上載者:User

標籤:

作用:用於對象的持久化,將對象寫到硬碟中,需要用的時候再還原序列化取出來。 
所謂序列化其實就是將程式中的資料(對象)通過某種方式,儲存到本地中。 
然後可以在程式關閉之後還儲存程式的某個執行狀態,方便在程式下次 
執行的時候通過"還原序列化"讀取出來,並且能夠還原資料的類型,從而延續程式退出時的狀態。 
一般來說,我們會使用序列化儲存一些需要持久化的資料,當然如果這個資料會比較龐大的話, 
我們就直接使用資料庫了!所以,序列化實際上目前很多領域用的已經不多了,大部分使用 
都已被資料庫替代了! 

如何序列化和還原序列化:

通過實現Serializable 介面來實現序列化

public class Person implements Serializable{ private String name; private String sex; public Person(String name,String sex){ this.name=name; this.sex=sex; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; }    } 
public class TestDemo { public static void main(String[] args) { //建立一個對象 Person people = new Person("張三","男"); try { //執行個體化ObjectOutputStream對象 ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("C:\\person.txt")); //將對象寫入檔案 oos.writeObject(people); oos.flush(); oos.close(); //執行個體化ObjectInputStream對象 ObjectInputStream ois=new ObjectInputStream(new FileInputStream("C:\\person.txt")); try { //讀取對象people,還原序列化 Person p = (Person)ois.readObject(); System.out.println("姓名:"+p.getName()); System.out.println("性別:"+p.getSex()); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } 

 

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.