我有来自DZone(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套接字传输序列化对象?以及如何将序列化/反序列化对象存储到字节数组中。
发布于 2013-10-16 04:00:24
这是用于向字节数组/从字节数组序列化的代码。我从- 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());
}发布于 2013-10-16 03:15:41
如何使用Java套接字传输序列化对象?
将其输出流包装在ObjectOutputStream中。
以及如何将序列化/反序列化对象存储到字符串中。
没有。序列化对象是二进制的,应该存储在字节数组中。反序列化对象是对象本身,而不是字符串。
您不需要那些readObject()和writeObject()方法。他们不会做默认情况下不会发生的事情。
发布于 2013-10-16 03:13:45
就像用对象流类包装filestream一样,对套接字也是如此。您应该将而不是“存储”序列化对象到字符串。
https://stackoverflow.com/questions/19394555
复制相似问题