我用ObjectInputStream的public final void writeObject(Object obj) throws IOException方法,读取对象的时候,不能知道什么时候读到末尾了,或者说能不能知道需要一共读几个对象?

解决方案 »

  1.   

    while(len=in.read(buf)!=-1)
    {}
    这样对OBJECT的流不行?
      

  2.   

    对不起,前面打错了,是readObject方法读取对象,不是writeObject.
      

  3.   

    to liang8305(七分之雨后):这样可以的,但是我还是不知道这个缓存里面有多少Object的。
      

  4.   

    只能自己做个count了。
    JAVA好象没有提供过此类方法。
      

  5.   

    使用readObject()可以自动一个接一个的读出Object,当读到末尾时还继续读会有EOFException被抛出。(我暂时没有找到可以判断是否到stream末尾的函数。)可以参看如下代码片断。// define a byte array to store the data. just as a file. 
    ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
    // object Stream for output. 
    ObjectOutputStream oos = new ObjectOutputStream(bos); 
    // write some objects...
    oos.writeObject(new Integer(23)); 
    oos.writeObject(new Boolean(true)); 
    oos.writeObject("abcd"); 
    oos.flush(); 
    // this is the data. 
    byte[] b = bos.toByteArray(); 
    oos.close(); 
    // define a byte array input stream to read data. just as a file. 
    ByteArrayInputStream bis = new ByteArrayInputStream(b); 
    // object input stream to read objects. 
    ObjectInputStream ois = new ObjectInputStream(bis); 
    // read until EOF. 
    while(true) {
        try {
         System.out.println(ois.readObject()); 
        } catch (EOFException e) {
            System.out.println("No more objects can be read."); 
            break; 
        }
    }
    ois.close(); ------输出结果-----
    23
    true
    abcd
    No more objects can be read.
      

  6.   

    补充:如果要看看里面有多少Object,只需要在上面代码的while循环中加入一个计数器(count++;)就行了。
    int count = 0; 
    while(true) {
        try {
         System.out.println(ois.readObject()); 
         count++; // add this after read object. 
        } catch (EOFException e) {
            System.out.println("No more objects can be read."); 
            break; 
        }
    }
      

  7.   

    while (true) {
        Object o = input.readObject();
        System.out.println(o);
      }
    } catch (EOFException e) {}