把多个类对像存到一个文件里,然后怎么把它门全都读出来
往里写多个对象可以,但是读的时候只能读出一个,并且都是第一个对象
如何解决

解决方案 »

  1.   

    我通过下面代码写入:
    import java.io.ObjectOutputStream;
    import java.io.FileOutputStream;
    import java.io.Serializable;public class Test {
    public static void main(String[] args)  throws Exception{
    ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("a.txt"));
    A a = new A();
    a.a = 20;
    oos.writeObject(a);
    B b = new B();
    b.b = 10;
    oos.writeObject(b);
    }
    }
    class A implements Serializable
    {
    int a = 100;
    }
    class B implements Serializable
    {
    int b = 200;
    }---------------------------------
    然后用下面的代码读出,没有问题
    import java.io.ObjectInputStream;
    import java.io.FileInputStream;
    public class ReadObject {
    public static void main(String[] args) throws Exception{
    ObjectInputStream ois = new ObjectInputStream(new FileInputStream("a.txt"));
    A a =(A) ois.readObject();
    System.out.println(a.a);
    B b = (B) ois.readObject();
    System.out.println(b.b);
    }
    }