Possible Duplicate:
Converting any object to a byte array in java
I have a class that needs to be cached. The cache API provides an interface that caches byte[]
. My class contains a field as List<Author>
, where Author
is another class. What is the correct way for me to turn List<Author>
to byte[]
for caching? And retrieve the byte[]
from cache to reconstruct the List<Author>
?
More detail about Author
class: it is very simple, only has two String
fields. One String
field is possible to be null
.
Write the contents of the object to the output stream using the writeObject() method of the ObjectOutputStream class. Flush the contents to the stream using the flush() method. Finally, convert the contents of the ByteArrayOutputStream to a byte array using the toByteArray() method.
Double is a higher datatype compared to byte. Therefore, double value will not be converted into byte implicitly, you need to convert it using the cast operator.
We can use String class getBytes() method to encode the string into a sequence of bytes using the platform's default charset. This method is overloaded and we can also pass Charset as argument. Here is a simple program showing how to convert String to byte array in java.
Converting byte array into Object and Object into a byte array process is known as deserializing and serializing. The class object which gets serialized/deserialized must implement the interface Serializable. Serializable is a marker interface that comes under package 'java. io.
Author class should implement Serializable
Then you can use ObjectOutputStream
to serialize the object and ByteArrayOutputStream
to get it written as bytes.
Then deserialize it using ObjectInputStream and convert back.
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(list);
byte[] bytes = bos.toByteArray();
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