序列化和反序列化

来源:互联网 发布:windows git 自动更新 编辑:程序博客网 时间:2024/05/20 02:55

定义一个Student类

    package com.jieke.io;      import java.io.Serializable;            /**      *Title:学生类      *Description:实现序列化接口的学生类      *Filename: Student.java      *@version 1.0      */      public class Student implements Serializable      {       private String name;       private char sex;       private int year;       private double gpa;             public Student()       {             }       public Student(String name,char sex,int year,double gpa)       {        this.name = name;        this.sex = sex;        this.year = year;        this.gpa = gpa;       }             public void setName(String name)       {        this.name = name;       }             public void setSex(char sex)       {        this.sex = sex;       }             public void setYear(int year)       {        this.year = year;       }             public void setGpa(double gpa)       {        this.gpa = gpa;       }             public String getName()       {        return this.name;       }              public char getSex()       {        return this.sex;       }             public int getYear()       {        return this.year;       }             public double getGpa()       {        return this.gpa;       }      }  

把student对象序列化到d:\\Student.txt

    import java.io.*;            /**      *Title:应用学生类      *Description:实现学生类实例的序列化与反序列化      *Filename: UseStudent.java      *@version 1.0      */            public class UseStudent      {       public static void main(String[] args)       {        Student st = new Student("Tom",'M',20,3.6);        File file = new File("d:\\Student.txt");        try        {         file.createNewFile();        }        catch(IOException e)        {         e.printStackTrace();        }        try        {         //Student对象序列化过程         FileOutputStream fos = new FileOutputStream(file);         ObjectOutputStream oos = new ObjectOutputStream(fos);         oos.writeObject(st);         oos.flush();         oos.close();         fos.close();               //Student对象反序列化过程         FileInputStream fis = new FileInputStream(file);         ObjectInputStream ois = new ObjectInputStream(fis);         Student st1 = (Student) ois.readObject();         System.out.println("name = " + st1.getName());         System.out.println("sex = " + st1.getSex());         System.out.println("year = " + st1.getYear());         System.out.println("gpa = " + st1.getGpa());         ois.close();         fis.close();        }        catch(ClassNotFoundException e)        {         e.printStackTrace();        }        catch (IOException e)        {         e.printStackTrace();        }                    }      }  

总结:

1)Java序列化就是把对象转换成字节序列,而Java反序列化就是把字节序列还原成Java对象。

2)采用Java序列化与反序列化技术,一是可以实现数据的持久化,在MVC模式中很是有用;二是可以对象数据的远程通信。

原创粉丝点击