Suppose I have an OutputStream
(and not an ObjectOutputStream
). Is is possible to send a serialized object using the write method? Thanks!
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.
You could use ObjectOutputStream to 'capture' the objects data in a byte Array and send this to the OutputStream.
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.
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();
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With