java IO操作与字节流(五)对象序列化

来源:互联网 发布:淘宝店库存管理 编辑:程序博客网 时间:2024/06/02 13:59

对象序列化应用实例:
(1)import java.io.*;


public class objectio {
    public static void main(String[] args)throws Exception
    {
        employee e1=new employee("qy1",23,3456);
        employee e2=new employee("qy2",26,5346);
        employee e3=new employee("qy3",24,5678);
        FileOutputStream f=new FileOutputStream("object.txt");
        ObjectOutputStream o=new ObjectOutputStream(f);
        o.writeObject(e1);
        o.writeObject(e2);
        o.writeObject(e3);
        FileInputStream f2=new FileInputStream("object.txt");
        ObjectInputStream oi=new ObjectInputStream(f2);
        employee e;
        for(int i=0;i<3;i++)
        {
            e=(employee)oi.readObject();  //读取对象,构造时用不到其构造方法;
            System.out.println(e.name+"  "+e.age+"  "+e.salary);
        }
    }

}
class employee implements Serializable{
    String name;
    int age;
    int salary;
    employee(String name,int age,int salary)
    {
        this.age=age;
        this.name=name;
        this.salary=salary;
       
    }
   
}
(2)当一个对象被序列化时,只能保存非静态的成员,而静态的成员和方法不被保存:
(3)如果被序列化的成员有对象,如果对象成员可序列化,则其对象成员也被保存,否则,抛出异常,可通过transient标记,不对该对象序列化;