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