pro*_*eek 4 java serialization
我有来自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());
}
}
Run Code Online (Sandbox Code Playgroud)
如何使用Java套接字传输序列化对象?还有如何将序列化/反序列化对象存储到字节数组中/从字节数组存储.
这是用于序列化到/从字节数组的代码.我得到了一些提示--Java Serializable Object to Byte Array
@Test
public void testByteArray() throws IOException, ClassNotFoundException, InterruptedException {
Hello h = new Hello();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput out = new ObjectOutputStream(bos);
out.writeObject(h);
byte b[] = bos.toByteArray();
out.close();
bos.close();
Hello h2;
ByteArrayInputStream bis = new ByteArrayInputStream(b);
ObjectInput in = new ObjectInputStream(bis);
h2 = (Hello) in.readObject();
assertTrue(10 == h2.getX());
assertTrue(20 == h2.getY());
}
Run Code Online (Sandbox Code Playgroud)