Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize/Deserialize Java object through network and byte array

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());
    }
}

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

like image 959
prosseek Avatar asked Dec 16 '22 05:12

prosseek


2 Answers

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());
}
like image 122
prosseek Avatar answered May 11 '23 00:05

prosseek


How can I transfer serialized object using Java socket?

Wrap its output stream in an ObjectOutputStream.

And also how can I store the serialized/deserialized object to/from a string.

You don't. Serialized objects are binary, and should be stored in byte arrays. A deserialized object is the object itself, not a string.

You don't need those readObject() and writeObject() methods. They don't do anything that wouldn't happen by default.

like image 45
user207421 Avatar answered May 10 '23 23:05

user207421