zoukankan      html  css  js  c++  java
  • 序列化与反序列化

    1、需要被序列化的对象必须实现Serializable接口。当一个类实现,那么他的子类可以不用在次实现。

    2、student类:注意transient关键词。可以取消默认的序列化行为。

    package cd.itcast.test;
    
    import java.io.Serializable;
    //必须实现这个接口
    public class Student implements Serializable{
        private String stuid;
        private String stuname;
        private transient int stuage;
        public String getStuid() {
            return stuid;
        }
        public void setStuid(String stuid) {
            this.stuid = stuid;
        }
        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;
        }
        
        public Student(String stuid, String stuname, int stuage) {
            this.stuid = stuid;
            this.stuname = stuname;
            this.stuage = stuage;
        }
        @Override
        public String toString() {
            return "ObjectSeriaDemo1 [stuid=" + stuid + ", stuname=" + stuname
                    + ", stuage=" + stuage + "]";
        }
    }

    3、测试代码

    package cd.itcast.test;
    
    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";
            //对象序列化
            /*ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
            Student student = new Student("110","张三",20);
            oos.writeObject(student);
            oos.close();*/
            //对象反序列化
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
            Student stu = (Student)ois.readObject();
            System.out.println(stu.toString());
            ois.close();
        }
    }
  • 相关阅读:
    java基础(二):补充
    java基础(二):变量和数据类型
    C基础系列(一)
    java基础(一)
    循环小数(Repeating Decimals)
    DNA序列(DNA Consensus String)
    sqlserver~创建函数
    docker简介和安装
    JMeter(6)、实现Java请求
    JMeter(5)、测试数据库
  • 原文地址:https://www.cnblogs.com/h-g-f-s123/p/6134201.html
Copyright © 2011-2022 走看看