Java序列化的一個例子

來源:互聯網
上載者:User

標籤:java序列化

學習Java這麼久,雖然腦子中有關於序列化的理解,但沒實際應用過,剛好碰到朋友要幫忙做個作業,就趁機寫一個很簡單的例子。


import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.io.Serializable;/** * 對象的序列化主要有兩種用途: 1) 把對象的位元組序列永久地儲存到硬碟上,通常存放在一個檔案中; 2) 在網路上傳送對象的位元組序列。 *//** * 要使對象序列化,就令該對象繼承java.io.Serializable類。 *//** * @author Jim * @Time 2016年4月14日 下午1:47:48 * */public class Program21 {public static void main(String[] args){try{//序列化對象,將對象儲存在student.dat中ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("student.dat"));Student s1 = new Student("Lisa", 20);out.writeObject(s1);//寫入對象out.close();//將student.dat中的對象還原序列化並print information.ObjectInputStream in = new ObjectInputStream(new FileInputStream("student.dat"));Student s2 = (Student)in.readObject();//讀出對象System.out.print("Student‘s name is " + s2.getName() + " and the age is " + s2.getAge());in.close();}catch(Exception e){e.printStackTrace();}}}/** * 定義一個學生類來繼承java.io.Serializable */class Student implements Serializable {private String name = "";private int age = 0;public Student(String name, int age) {this.name = name;this.age = age;}public String getName(){return this.name;}public int getAge() {return this.age;}}


本文出自 “A&D_Ro535” 部落格,請務必保留此出處http://ro535.blog.51cto.com/11279790/1763771

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.