java对象的序列化输出跟读取

java对象的序列化输出和读取

被序列化的对象

 

package JavaIo;

import java.io.Serializable;

/**
 *
 * @author zhyq
 */
public class Person implements Serializable {

    transient private String birth; //该值无法被序列化
    private String name;

    public String getBirth() {
        return birth;
    }

    public void setBirth(String birth) {
        this.birth = birth;
    }

    public String getName() {
        return name;
    }

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

 

对象的序列化输出和读取

 

package JavaIo;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 *
 * @author zhyq
 */
public class Main {

    public static void main(String[] args) {
        FileOutputStream fileOutStream = null;  //底层文件输出流
        ObjectOutputStream objectOut = null;  //高层的对象输出流
        Person p = new Person();
        p.setName("jone");
        p.setBirth("1936");
        try {
            fileOutStream = new FileOutputStream("object.ser");
            objectOut = new ObjectOutputStream(fileOutStream); //用底层的文件输出流对象装饰高层的对象输出流
            objectOut.writeObject(p);  //序列化对象
            objectOut.close();
        } catch (Exception e) {
            
        }

        Person pToNew = null;
        FileInputStream fileInputStream=null;  //底层的文件读取流
        ObjectInputStream objectIn = null; //高层的对象读取流
        try {
            fileInputStream = new FileInputStream("object.ser"); //
            objectIn = new ObjectInputStream(fileInputStream);//用底层的文件读取流装饰高层的对象读取流
            pToNew = (Person)objectIn.readObject();//读取序列化的对象并设置
        } catch (Exception e) {
        }

        System.out.println("birth 被设置成transient 值为   "+pToNew.getBirth());
        System.out.println("name 没有进行特殊的设置,值为   "+pToNew.getName());
    }
}