码迷,mamicode.com
首页 > 编程语言 > 详细

Java序列化技术

时间:2017-09-02 12:12:23      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:计算   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序列化技术

标签:计算   cep   int   年龄   ted   serial   pre   setname   rgs   

原文地址:http://www.cnblogs.com/m2492565210/p/7466153.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!