我正在尝试验证我的自定义 Java 对象是否已正确序列化/反序列化,并且我可以将此序列化机制与文件、流等一起使用。这是我创建的测试。这是正确的做法吗?
public class SerializableTest {
@Test public void shouldSerialize() throws Exception {
Foo foo = new Foo(123);
// serialize it to a string
ByteArrayOutputStream out = new ByteArrayOutputStream();
new ObjectOutputStream(out).writeObject(foo);
String written = out.toString();
// read it back
ByteArrayInputStream in = new ByteArrayInputStream(written.getBytes());
Foo foo2 = (Foo)(new ObjectInputStream(in).readObject());
// check that two objects are identical
assertEquals(foo, foo2);
}
}
Run Code Online (Sandbox Code Playgroud)
这里有什么问题吗?
代替
String written = out.toString();
Run Code Online (Sandbox Code Playgroud)
和
byte[] written = out.toByteArray();
Run Code Online (Sandbox Code Playgroud)
您不能将随机二进制数据存储为字符串。字符串用于文本。
| 归档时间: |
|
| 查看次数: |
1279 次 |
| 最近记录: |