我有来自 DZone(http://www.dzone.com/links/r/java_custom_serialization_example.html)的代码,它从/到文件中序列化/反序列化 Java 对象。
final class Hello implements Serializable
{
int x = 10;
int y = 20;
public int getX()
{
return x;
}
public int getY()
{
return y;
}
}
public class SerializedComTest {
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
@Test
public void testFile() throws IOException, ClassNotFoundException {
Hello h = new Hello();
FileOutputStream bs = new FileOutputStream("hello.txt"); // ("testfile");
ObjectOutputStream out = new ObjectOutputStream(bs);
out.writeObject(h);
out.flush();
out.close();
Hello h2;
FileInputStream fis = new FileInputStream("hello.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
h2 = (Hello) ois.readObject();
assertTrue(10 == h2.getX());
assertTrue(20 == h2.getY());
}
}
如何使用 Java 套接字传输序列化对象?以及如何将序列化/反序列化对象存储到字节数组中。