2014-12-27 70 views
1

我写一个程序,对象序列化到一个名为“Books.ser”查看文档,而对象序列化

FileOutputStream fos = new FileOutputStream("Books.ser"); 
ObjectOutputStream os = new ObjectOutputStream(fos); 
for (int i = 1; i < 1000; i++) { 
    os.writeObject(shelf.book[i]); 
} 
os.close(); 

文件有没有办法打开和查看这个文件? 如果不是,我只想知道Java是否序列化尚未初始化的对象。 (null)

+1

是的,java会序列化空值。当你读对象时,将其转换回原来的形式,以便与之交互。一种简单的方法来检查是否写入空值是在写入之前检查变量是否包含对象 – 2014-12-27 19:37:49

+1

而不是序列化数组的所有元素,您可以序列化数组(将序列化它的元素) – 2014-12-27 19:47:01

+0

只需确认,何时我序列化对象,他们的变量序列化以及?例如,如果有:String dueDate将shelf.book [i] .dueDate被序列化? – noobProgrammer 2014-12-27 20:00:22

回答

1

那么,相反的循环应该做的。

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)InputStreamOutputStream类。

try (ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("Books.ser"))) { 
    // loop and serialize... 
} catch (IOException e) { 
    // Handle exception 
} 
+0

噢,我做到了。我只是想知道,如果Java序列化,然后反序列化尚未初始化的对象(空)。 – noobProgrammer 2014-12-27 19:47:28

+0

@noobProgrammer - gotcha!我更新了答案以提供更详细的答案。属性也被序列化/反序列化,空值被处理(参见提供的测试用例)。 – wassgren 2014-12-28 10:05:39