java編程筆記17 對象序列化

來源:互聯網
上載者:User

在前面我們學習了用一些特定的方法可以將int,double等類型的資料進行輸入輸出處理。現在假設我們有一個Student類,每個Student對象包含了姓名,語文,數學,英語的成績。姓名是String類型,成績是int類型,現在想把Student對象的資料儲存下來,你會想到什麼辦法?當然,用前面的辦法可以用writeInt等方法輸出到檔案中,用readInt等方法從檔案中讀出來,可是如果我們遇到一個不止思想資料的對象呢???

對象序列化就是直接把整個對象做輸入輸出處理,java提供了一種機制來完成這個工作,它的名字就叫序列化Serialization,簡單的說,就是把對象中的屬性,按照流的方法來做輸入輸出處理,這裡要注意,只有屬性可以做序列化處理,因為屬性是變數,可以儲存資料,方法是程式碼,做輸出輸入處理沒有意義。

只要一個類實現了Serializable介面,這個類的對象就可以序列化,Serializable介面是個標記介面,標記介面是指沒有定義任何的成員,簡單地說就是一個空介面,在前面學習對象複製的時候Cloneable介面也是空介面。實現標記介面的類內部不需要做任何改變(介面沒有方法讓它去實現);

下面我們來寫一個可以序列化的類:(這裡有個問題,結果在檔案裡是亂碼,不過不影響再從檔案擷取資料)

package ch21;import java.io.*;//Student類實現了Serializable介面,所以它的對象可以序列化輸入輸出public class Student implements Serializable{private String name;private int chScore, engScore;private transient int mathScore;//transient用於修飾希望在序列化過程中不想被序列化的屬性public Student(String n, int c, int e, int m){name = n;chScore = c;engScore = e;mathScore = m;}public double avgScore(){return (chScore+engScore+mathScore)/3.0;}public void printData(){ System.out.println("姓名:"+name); System.out.println("語文:"+chScore); System.out.println("英文:"+engScore); System.out.println("數學:"+mathScore); System.out.println("平均:"+avgScore());}}

寫一個類來寫序列化資料:

package ch21;import java.io.*;public class ObjectSerializationExample1{public static void main(String argv[]){int c = Integer.parseInt(argv[1]);int e = Integer.parseInt(argv[2]);int m = Integer.parseInt(argv[3]);Student st = new Student(argv[0], c, e, m);st.printData();try {FileOutputStream fout = new FileOutputStream("C:\\Data.txt");ObjectOutputStream objOut = new ObjectOutputStream(fout);//資料流串連機制!!!objOut.writeObject(st);//寫序列化對象objOut.close();fout.close();}catch (IOException ie){System.err.println(e);}}}

讀出序列化資料:

package ch21;import java.io.*;public class ObjectSerializationExample2{public static void main(String argv[]){try {FileInputStream fin = new FileInputStream("Data.txt");ObjectInputStream objIn = new ObjectInputStream(fin);//資料流串連!!!Student st = (Student)objIn.readObject();//擷取序列化資料st.printData();objIn.close();fin.close();}catch (Exception e){System.err.println(e);}}}

結果:

姓名:java
語文:90
英文:80
數學:0
平均:56.666666666666664

可以看transient關鍵字發生了作用


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.