• Java基础IO流(四)序列化与反序列化


    对象的序列化与反序列化:

    对象的序列化,就是将Object转换成byte序列,反之叫对象的反序列化。

    序列化流(ObjectOutInputStream),是过滤流  -------writeObject

    反序列化流(ObjectInputStream)-----raedObject

    序列化接口(Serializable)

      对象必须实现序列化接口,才能进行序列化,否则出现异常

          这个接口,没有任何方法,只是一个标准。

    案例描述:Student,将它序列化到文件中,再反序列化读出。

    Student类:

    package Blog;
    
    import java.io.Serializable;
    
    public class Student implements Serializable{
    
        private String stuno;
        private String stuname;
        private int stuage;
    
        
        
        public Student(String stuno, String stuname, int stuage) {
            super();
            this.stuno = stuno;
            this.stuname = stuname;
            this.stuage = stuage;
        }
    
        public Student() {
            super();
        }
    
        public String getStuno() {
            return stuno;
        }
    
        @Override
        public String toString() {
            return "Student [stuno=" + stuno + ", stuname=" + stuname + ", stuage=" + stuage + "]";
        }
    
        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;
        }
    
    }

    序列化Student到obj.dat中

    package Blog;
    
    import java.io.FileOutputStream;
    import java.io.ObjectOutputStream;
    
    public class ObjectSeriaDemo1 {
        
        public static void main(String[] args) throws Exception{
            String file = "obj.dat";
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
            
            Student stu = new Student("1001","zhangsan",20);
            oos.writeObject(stu);
            oos.flush();
            oos.close();
    
        }
    }

    反序列化obj.dat

    package Blog;
    
    import java.io.FileInputStream;
    import java.io.ObjectInputStream;
    
    public class ObjectSeriaDemo1 {
        
        public static void main(String[] args) throws Exception{
            String file = "obj.dat";
            
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
            Student stu = (Student)ois.readObject();
            System.out.println(stu);
            ois.close();
        }
    }

  • 相关阅读:
    Yarn的三种调度器
    tcpdump 常用用法
    Openssh升级脚本
    RAID详解及软RAID管理
    zabbix安装部署
    Linux根分区、SWAP分区扩容
    Windows server 2012 控制面板打不开防火墙
    Windows Server 设置时间同步出错问题
    Windows dos命令激活系统
    Swap分区大小设置
  • 原文地址:https://www.cnblogs.com/deepSleeping/p/10067747.html
Copyright © 2020-2023  润新知