通过网络和字节数组序列化/反序列化Java对象 [英] Serialize/Deserialize Java object through network and byte array

查看:70
本文介绍了通过网络和字节数组序列化/反序列化Java对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从 DZone(http://www.dzone.com/links/r/java_custom_serialization_example.html) 从/到文件序列化/反序列化 Java 对象.

I have this code from DZone(http://www.dzone.com/links/r/java_custom_serialization_example.html) that serialize/deserialize Java object from/to file.

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 套接字传输序列化对象?以及如何将序列化/反序列化的对象存储到/从字节数组中存储.

How can I transfer serialized object using Java socket? And also how can I store the serialized/deserialized object to/from a byte array.

推荐答案

这是字节数组序列化的代码.我得到了提示 - Java Serializable Object to Byte Array

This is the code for serialization to/from byte array. I got hints from - 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());
}

这篇关于通过网络和字节数组序列化/反序列化Java对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆