• Java 序列化


    序列化(对象写入文件)   反序列化(从文件读取对象)

    public class Demo01 {

    public static void main(String[] args) throws IOException, ClassNotFoundException {

    //序列化 对象写入文件

    FileOutputStream fos=new FileOutputStream("D:\person.txt");

    ObjectOutputStream oos=new ObjectOutputStream(fos);//序列化

    Person p=new Person("zhangsan",18); //对象  需要实现接口

    oos.writeObject(p);   //写入对象  对象可为 存储Person的集合

    oos.close();

    //反序列化 从文件中读出对象

    FileInputStream fis=new FileInputStream("D:\person.txt");

    ObjectInputStream ois=new ObjectInputStream(fis);

    try {

    while(true) { //Person.class丢失ClassNotFoundException

    Object obj = ois.readObject(); //读取对象

    Person p2=(Person)obj; //Person类型

    System.out.println(p2); //输出 调用p2.toString()

    }

    } catch(EOFException e) {

    System.out.println("读到了文件的末尾");

    }

    ois.close();

    }

    }

    public class Person implements Serializable{//实现(标记类)接口  无抽象方法    

    private String name; //对象才可以序列化

    //private int age;

    //private static int age;//静态修饰  是类的数据 也不会被序列化

    private transient int age;//瞬态关键字transient修饰的属性不会序列化

    private static final long serialVersionUID=4321L;//序列化号写死

    //修改Person类后也能反序列化

    public String getName(){return name;}

    public void setName(String name){this.name = name;}

    public int getAge(){return age;}

    public void setAge(int age){this.age = age;}

    public Person(){super();}

    public Person(String name, int age) {

    super();

    this.name = name;

    this.age = age;

    }

    @Override

    public String toString() {

    return "Person [name=" + name + ", age=" + age + "]";

    }

    }

  • 相关阅读:
    sqlISNULL函数(转载)
    sql数据导入导出(转载)
    sqlbcp
    SQL连接方式(左连接、右连接、全连接)转载
    陶哲轩实分析 习题 7.2.6 (嵌套级数)
    陶哲轩实分析 命题7.2.5 证明
    陶哲轩实分析 定义 7.2.1(形式无限级数) 的一点注记
    陶哲轩实分析 推论 7.3.2 (比较判别法) 证明
    陶哲轩实分析 习题 7.2.6 (嵌套级数)
    陶哲轩实分析 命题 7.2.14 (极限算律) 证明
  • 原文地址:https://www.cnblogs.com/javscr/p/10248726.html
Copyright © 2020-2023  润新知