欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

序列化基本操作

程序员文章站 2022-04-04 09:09:55
...
一 介绍
1、对象的序列化,就是将Object转换成byte序列,反之叫对象的反序列化
2、序列化流(ObjectOutputStream),是过滤流。---writeObject
3、反序列化流(ObjectInputStream) ---readObject
4、序列化接口(Serializable)
对象必须实现序列化接口,才能进行序列化,否则将出现异常。
这个接口,没有任何方法,只是一个标准。
 
二 实例
1、需要序列化的类
package com.imooc.io;
 
import java.io.Serializable;
 
public class Student implements Serializable{
    private String stuno;
    private String stuname;
    //该元素不会进行jvm默认的序列化,也可以自己完成这个元素的序列化
    private transient int stuage
    
    public Student(String stuno, String stuname, int stuage) {
         super();
         this.stuno = stuno;
         this.stuname = stuname;
         this.stuage = stuage;
    }
 
    public String getStuno() {
         return stuno;
    }
    public void setStuno(String stuno) {
         this.stuno = stuno;
    }
    public String getStuname() {
         return stuname;
    }
    public void setStuname(String stuname) {
         this.stuname = stuname;
    }
    public int getStuage() {
         return stuage;
    }
    public void setStuage(int stuage) {
         this.stuage = stuage;
    }
    @Override
    public String toString() {
         return "Student [stuno=" + stuno + ", stuname=" + stuname + ", stuage="
                 + stuage + "]";
    }
     private void writeObject(java.io.ObjectOutputStream s)
                 throws java.io.IOException{
          s.defaultWriteObject();//把jvm能默认序列化的元素进行序列化操作
          s.writeInt(stuage);//自己完成stuage的序列化
     }
     private void readObject(java.io.ObjectInputStream s)
                 throws java.io.IOException, ClassNotFoundException{
           s.defaultReadObject();//把jvm能默认反序列化的元素进行反序列化操作
           this.stuage = s.readInt();//自己完成stuage的反序列化操作
    }
}
2、测试代码
package com.imooc.io;
 
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
 
public class ObjectSeriaDemo1 {
    public static void main(String[] args) throws Exception{
         String file = "demo/obj.dat";
         //1.对象的序列化
         ObjectOutputStream oos = new ObjectOutputStream(
                 new FileOutputStream(file));
         Student stu = new Student("10001", "张三", 20);
         oos.writeObject(stu);
         oos.flush();
         oos.close();
         ObjectInputStream ois = new ObjectInputStream(
                 new FileInputStream(file));
         Student stu1 = (Student)ois.readObject();
         System.out.println(stu1);
         ois.close(); 
    }   
}
 
三 运行结果

 

Student [stuno=10001, stuname=张三, stuage=20]
相关标签: 序列化