Android-IO流之对象操作流ObjectInputStream/ObjectOutputStream

目录

  1. ObjectInputStream/ObjectOutputStream对象操作流
    --12.1 ObjectInputStream 对象操作输入流/反序列化
    --12.2 ObjectOutputStream 对象操作输出流/序列化

12.ObjectInputStream/ObjectOutputStream对象操作流

可以进行序列化/反序列化,将一个对象写出,或者将一个序列化的对象读入。

12.1 ObjectInputStream 对象操作输入流/反序列化

  1. ObjectInputStream构造方法
public ObjectInputStream(InputStream in)
  1. ObjectInputStream重要方法
public final Object readObject()
  1. ObjectInputStream使用
public class Person implements Serializable {
    private String name;
    private String age;

    public Person(String name, String age) {
        this.name = name;
        this.age = age;
    }
    ...
}
        File dir = Environment.getExternalStorageDirectory();
        File dst = new File(dir, "dst4.txt");
        
        FileInputStream fis = new FileInputStream(dst);
        ObjectInputStream ois = new ObjectInputStream(fis);
        Person person = (Person) ois.readObject();//Person一定要实现Serializable接口才可序列化
        Log.d("xl", person.toString());
        ois.close();

12.2 ObjectOutputStream 对象操作输出流/序列化

  1. ObjectOutputStream构造方法
public ObjectOutputStream(OutputStream out)
  1. ObjectOutputStream重要方法
public final void writeObject(Object obj)
  1. ObjectOutputStream使用
public class Person implements Serializable {
    private String name;
    private String age;

    public Person(String name, String age) {
        this.name = name;
        this.age = age;
    }
    ...
}
        File dir = Environment.getExternalStorageDirectory();
        File dst = new File(dir, "dst4.txt");

        FileOutputStream fos = new FileOutputStream(dst);
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        Person p = new Person("a", "1"); //Person一定要实现Serializable接口才可序列化
        oos.writeObject(p);
        oos.close();

你可能感兴趣的:(Android-IO流之对象操作流ObjectInputStream/ObjectOutputStream)