zoukankan      html  css  js  c++  java
  • 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 + "]";

    }

    }

  • 相关阅读:
    逆序数 POJ 2299 Ultra-QuickSort
    DP URAL 1244 Gentlemen
    找规律 SGU 107 987654321 problem
    找规律 SGU 126 Boxes
    DP VK Cup 2012 Qualification Round D. Palindrome pairs
    模拟 Coder-Strike 2014
    模拟 Codeforces Round #203 (Div. 2) C. Bombs
    DFS HDOJ 2614 Beat
    最短路(Floyd_Warshall) POJ 2240 Arbitrage
    最短路(Floyd_Warshall) POJ 1125 Stockbroker Grapevine
  • 原文地址:https://www.cnblogs.com/javscr/p/10248726.html
Copyright © 2011-2022 走看看