我吧一组对象序列化到了一个文件,当我读取这个文件反序列化的时候怎么知道有多少个对象呢?(也就是说怎么才能读取完全呢?)

解决方案 »

  1.   

    将所有要序列化的对象保存到容器,只要序列化这个容器就可以了
    比如,
    Student   stu   =   new   Student("wang");   //   创建一个对象
    Student   stu2   =   new   Student("...");   //   创建多个对象
    ....
    List   list   =   new   ArrayList();
    list.add(stu);
    list.add(stu2);
    ....ObjectOutputStream   oos   =   new   ObjectOutputStream(...);   //对象输出流
    oos.writeObject(list);
    oos.close();ObjectInputStream   ois   =   new   ObjectInputStream(...);   //对象输入流
    List   objectList   =   ois.readObject();
    ois.close(); 
      

  2.   

    ObjectInputStream在实例化这个类的对象的时候 会要求传入一个InputStream类的对象
    它在执行读取操作的时候 实际上用的是这个InputStream 所以检测这个InputStream的available方法 检测可读取的字节数
    只要它大于0 你就一直调用ObjectInputStream的readObject方法就行了。
    import java.io.*;public class test {
    public static void main(String[] args) {
    try {
    write();
    read();
    } catch (Exception e) {
    // TODO: handle exception
    e.printStackTrace();
    }
    }

    public static void write() {
    try {
    ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(new File("d:/a.txt")));
    student s = new student();
    s.setAddr("河北石家庄");
    s.setName("joejoe1991");
    out.writeObject(s);

    s = new student();
    s.setAddr("北京");
    s.setName("joejoe2008");
    out.writeObject(s);

    s = new student();
    s.setAddr("广东");
    s.setName("joejoe11");
    out.writeObject(s);
    out.flush();
    out.close();
    } catch (Exception e) {
    e.printStackTrace();
    }
    }

    public static void read() {
    try {
    FileInputStream stream = new FileInputStream(new File("d:/a.txt"));
    ObjectInputStream in = new ObjectInputStream(stream);
    while (stream.available() > 0) {
    student s = (student)in.readObject();
    System.out.println(s.getAddr());
    System.out.println(s.getName());
    System.out.println("********************");
    }
    stream.close();
    in.close();
    } catch (Exception e) {
    e.printStackTrace();
    }
    }
    }class student implements Serializable {
    private static final long serialVersionUID = 1L;
    private String name;
    private String addr;
    public String getAddr() {
    return addr;
    }
    public void setAddr(String addr) {
    this.addr = addr;
    }
    public String getName() {
    return name;
    }
    public void setName(String name) {
    this.name = name;
    }


    }