Java序列化技術

來源:互聯網
上載者:User

標籤:計算   cep   int   年齡   ted   serial   pre   setname   rgs   

用序列化來儲存物件。

先定義一個用來序列化的類:

 

package io.xuliehua;

import java.io.*;

public class Student implements Serializable{

    private String name;

    private String ID;

    private int age;

    private String specialty;

    public Student(String name, String ID, int age, String specialty){

        this.name=name;

        this.ID=ID;

        this.age=age;

        this.specialty=specialty;

    }

    

    public Student(){}

    

    public String getName() {

        return name;

    }

    public void setName(String name) {

        this.name = name;

    }

    

    public String getID() {

        return ID;

    }

    public void setID(String iD) {

        ID = iD;

    }

    

    public int getAge() {

        return age;

    }

    public void setAge(int age) {

        this.age = age;

    }

    

    public String getSpecialty() {

        return specialty;

    }

    public void setSpecialty(String specialty) {

        this.specialty = specialty;

    }

    

    public String toString(){

        return "姓名:"+name+"  學號:"+ID+"  年齡:"+age+"  專業:"+specialty;

    }

}

 

package io.xuliehua;

import java.io.*;

public class ObjectFileTest {

 

    public static void main(String[] args) {

        Student st = new Student("周勇","20140101",18,"電腦");

        try {

            ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("save.dat"));

            out.writeObject(st);

            out.close();

            ObjectInputStream in = new ObjectInputStream(new FileInputStream("save.dat"));

            Student pupil = (Student)in.readObject();

            in.close();

            System.out.println(pupil);

            System.out.println("姓名:"+pupil.getName());

            System.out.println("學號:"+pupil.getID());

            System.out.println("年齡:"+pupil.getAge());

            System.out.println("專業:"+pupil.getSpecialty());

        } catch (FileNotFoundException e) {

            // TODO Auto-generated catch block            e.printStackTrace();

        } catch (IOException e) {

            // TODO Auto-generated catch block            e.printStackTrace();

        } catch (ClassNotFoundException 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.