java学习笔记之IO编程—对象序列化

     对象序列化就是将内存中保存的对象以二进制数据流的形式进行处理,可以实现对象的保存或网络传输。

     并不是所有的对象都可以被序列化,如果要序列化的对象,那么对象所在的类一定要实现java.io.Serializable父接口,作为序列化的标记,这个接口没有任何方法,描述的是一种类的能力。

     java中提供了ObjectOutputStream(序列化) ObjectInputStream(反序列化)两个类

ObjectOutputStream的定义:

public class ObjectOutputStream extends OutputStream
implements ObjectOutput, ObjectStreamConstants

构造方法:

public ObjectOutputStream​(OutputStream out) throws IOException

主要方法:

public final void writeObject​(Object obj) throws IOException

ObjectInputStream的定义:

public class ObjectInputStream
extends InputStream
implements ObjectInput, ObjectStreamConstants

构造方法:

public ObjectInputStream​(InputStream in) throws IOException

主要方法:

public final Object readObject() throws IOException,ClassNotFoundException

 

transient关键字:

默认情况下当执行了对象系列化的时候会将类中的全部属性的内容进行全部的序列化操作,但是很多情况下有一些属性可能并不需要进行序列化的处理,这个时候就可以在属性定义上使用transient关键字来完成了

代码实例:实现序列化和反序列化

import java.io.*;

public class SerializableDemo {
    private static final File SAVE_FILE = new File("D:"+File.separator+"my.person");
    public static void main(String[] args) throws Exception {
        // TODO Auto-generated method stub
        saveObject(new Person("英格拉姆",22,"lakers"));
        System.out.println(loadObject());
    }
    public static void saveObject(Object o) throws Exception {
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(SAVE_FILE));
        oos.writeObject(o);
        oos.close();
    }
    public static Object loadObject() throws Exception{
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(SAVE_FILE));
        Object o = ois.readObject();
        ois.close();
        return o;
    }
}
class Person implements Serializable{
    private String name;
    private int age;
    private transient String team;
    public Person(String name , int age , String team) {
        this.name = name;
        this.age = age;
        this.team = team;
    }
    public String toString() {
        return "姓名:"+this.name+" 年龄:"+this.age+" 所在球队:"+this.team;
    }

 

posted @ 2020-02-04 00:09  幼儿猿班长  阅读(148)  评论(0编辑  收藏  举报