「Java」- 将对象写入文件,并从文件中读取

问题描述

在使用 Selenium 时,我们需要保存 Cookie 信息,以便于下次自动化测试时能够恢复(为了保存登录状态);

解决办法

我们可以将 Cookie 对象保存到文件中,然后下次自动化测试时再从文件中读取该对象;

为了表述问题,我们仅仅记录对象的保存和读取方法,而不会涉及 Selenium 细节;

将对象写入文件

Foo fooObject = new Foo()
new ObjectOutputStream(new FileOutputStream("/tmp/foo.bin")).writeObject(fooObject)

对文件读取对象

Foo fooObject = (Foo) new ObjectInputStream(new FileInputStream("/tmp/foo.bin")).readObject()

注意事项

在 Groovy 中,该方法并不适用,会产生 java.lang.ClassNotFoundException: com.k4nz.example.Foo 异常。解决方法参考 Groovy/Write an Object to File and Read it 笔记;

参考文献

How to Write an Object to File in Java
Java IO: ObjectInputStream