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();
        }
    }
  • 相关阅读:
    Swap Nodes in Pairs
    Permutations(copy)
    Sort Colors
    Merge Two Sorted Lists
    Implement Queue using Stacks
    Best Time to Buy and Sell Stock
    Happy Number
    Gray Code
    springMVC初次搭建,产生错误
    JSP常用指令
  • 原文地址:https://www.cnblogs.com/h-g-f-s123/p/6134201.html
Copyright © 2011-2022 走看看