关于 Java 对象序列化您不知道的 5 件事
2010-05-05 00:00:00 来源:WEB开发网将 Person 序列化后,很容易将对象状态写到磁盘,然后重新读出它,下面的 JUnit 4 单元测试对此做了演示。
清单 2. 对 Person 进行反序列化
public class SerTest
{
@Test public void serializeToDisk()
{
try
{
com.tedneward.Person ted = new com.tedneward.Person("Ted", "Neward", 39);
com.tedneward.Person charl = new com.tedneward.Person("Charlotte",
"Neward", 38);
ted.setSpouse(charl); charl.setSpouse(ted);
FileOutputStream fos = new FileOutputStream("tempdata.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(ted);
oos.close();
}
catch (Exception ex)
{
fail("Exception thrown during test: " + ex.toString());
}
try
{
FileInputStream fis = new FileInputStream("tempdata.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
com.tedneward.Person ted = (com.tedneward.Person) ois.readObject();
ois.close();
assertEquals(ted.getFirstName(), "Ted");
assertEquals(ted.getSpouse().getFirstName(), "Charlotte");
// Clean up the file
new File("tempdata.ser").delete();
}
catch (Exception ex)
{
fail("Exception thrown during test: " + ex.toString());
}
}
}
更多精彩
赞助商链接