那么,相反的循环应该做的。
FileInputStream is = new FileInputStream("Books.ser");
ObjectInputStream ois = new ObjectInputStream(is);
for (int i = 1; i < 1000; i++) {
Object o = os.readObject();
// Do something with o - e.g. add to a List
}
ois.close();
从JavaDoc:
一个ObjectOutputStream写入的基本数据类型和Java的图表对象到OutputStream。可以使用ObjectInputStream读取(重建)对象。对象的持久存储可以通过使用流的文件来完成。
所以,基本上你写原语(例如writeInt
)或与ObjectOutputStream
对象(writeObject
),然后你读回用ObjectInputStream
与相应read
- 方法。
如果OutputStream知道要被序列化的对象的类型,那么也可以与空值一起使用。例如。
public static class MyClass implements Serializable {
private final String content;
public MyClass(final String content) {
this.content = content;
}
public String getContent() {
return content;
}
}
@Test
public void testWriteObject() throws IOException, ClassNotFoundException {
MyClass nullInstance = null;
MyClass notNullInstance = new MyClass("This content is not null");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (ObjectOutputStream os = new ObjectOutputStream(baos)) {
os.writeObject(nullInstance);
os.writeObject(notNullInstance);
}
try (ObjectInputStream is =
new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()))) {
MyClass shouldBeNull = (MyClass) is.readObject();
MyClass shouldNotBeNull = (MyClass) is.readObject();
Assert.assertNull(shouldBeNull);
Assert.assertNotNull(shouldNotBeNull);
// Attributes are serialized too
Assert.assertEquals("This content is not null", shouldNotBeNull.getContent());
}
}
使用时,建议使用try-与资源结构(从Java 7)InputStream
和OutputStream
类。
try (ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("Books.ser"))) {
// loop and serialize...
} catch (IOException e) {
// Handle exception
}
是的,java会序列化空值。当你读对象时,将其转换回原来的形式,以便与之交互。一种简单的方法来检查是否写入空值是在写入之前检查变量是否包含对象 – 2014-12-27 19:37:49
而不是序列化数组的所有元素,您可以序列化数组(将序列化它的元素) – 2014-12-27 19:47:01
只需确认,何时我序列化对象,他们的变量序列化以及?例如,如果有:String dueDate将shelf.book [i] .dueDate被序列化? – noobProgrammer 2014-12-27 20:00:22