Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize object with outputstream

Suppose I have an OutputStream (and not an ObjectOutputStream). Is is possible to send a serialized object using the write method? Thanks!

like image 630
OckhamsRazor Avatar asked Nov 23 '11 10:11

OckhamsRazor


People also ask

How do you serialize an object?

To serialize an object means to convert its state to a byte stream so that the byte stream can be reverted back into a copy of the object. A Java object is serializable if its class or any of its superclasses implements either the java. io. Serializable interface or its subinterface, java.

What could you use to serialize an object obj and write it to a stream Outstream using binary serialization?

You could use ObjectOutputStream to 'capture' the objects data in a byte Array and send this to the OutputStream.

Does ArrayList implements serializable?

In Java, the ArrayList class implements a Serializable interface by default i.e., ArrayList is by default serialized. We can just use the ObjectOutputStream directly to serialize it.


2 Answers

Here is what you do to serialize the object:

new ObjectOutputStream(outputStream).writeObject(obj);

If you want to control the byte[] output:

ByteArrayOutputStream buffer = new ByteArrayOutputStream();

ObjectOutputStream oos = new ObjectOutputStream(buffer);

oos.writeObject(obj);

oos.close();

byte[] rawData = buffer.toByteArray();
like image 112
Dapeng Avatar answered Sep 19 '22 13:09

Dapeng


You could use ObjectOutputStream to 'capture' the objects data in a byte Array and send this to the OutputStream.

String s = "test";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream( baos );
oos.writeObject( s );
byte[] byteArray = baos.toByteArray();
for ( byte b : byteArray ) {
    System.out.print( (char) b );
}

Another non generic option would be to serialize the object in a string representation e.g. CSV

like image 37
stacker Avatar answered Sep 17 '22 13:09

stacker