to liang8305(七分之雨后):这样可以的,但是我还是不知道这个缓存里面有多少Object的。
只能自己做个count了。 JAVA好象没有提供过此类方法。
使用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.
补充:如果要看看里面有多少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; } }
while (true) { Object o = input.readObject(); System.out.println(o); } } catch (EOFException e) {}
{}
这样对OBJECT的流不行?
JAVA好象没有提供过此类方法。
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.
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;
}
}
Object o = input.readObject();
System.out.println(o);
}
} catch (EOFException e) {}