java的序列化之Externalizable接口

import java.io.Externalizable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;

public class Person implements Externalizable {

  private String name;
  private int age;

  public Person(){}

  public Person(String name, int age) {
    this.name = name;
    this.age = age;
  }

  @Override
  public String toString() {
    return "name is " + name + ", age is " + age;
  }

  @Override
  public void writeExternal(ObjectOutput out) throws IOException {
    out.writeObject(name);
    out.writeObject(age);
  }

  @Override
  public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
    this.name = (String)in.readObject();
    this.age = (int)in.readObject();
  }

  public static void main(String[] args) throws IOException {
    FileOutputStream fos = null;
    ObjectOutputStream oos = null;
    FileInputStream fis = null;
    ObjectInputStream ois = null;

    try {
      fos = new FileOutputStream(new File("/tmp/123456.txt"));
      oos = new ObjectOutputStream(fos);
      oos.writeObject(new Person("sunwukong", 600));
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } finally {
      if (oos != null) {
        oos.close();
      }
    }

    try {
      fis = new FileInputStream(new File("/tmp/123456.txt"));
      ois = new ObjectInputStream(fis);
      Person per = (Person)ois.readObject();
      System.out.println(per);
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (ois != null) {
        ois.close();
      }
    }
  }
}

 

posted @ 2020-04-22 09:59  kissrule  阅读(201)  评论(0编辑  收藏  举报