Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java, how to convert a list of objects to byte array? [duplicate]

Tags:

java

caching

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.

like image 633
Steve Avatar asked Jan 03 '13 18:01

Steve


People also ask

How do you create a byte array of objects in java?

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.

Can we cast double to byte in java?

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.

Can we convert string to byte array in java?

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.

How do you convert bytes to objects?

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.


1 Answers

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();
like image 149
Subin Sebastian Avatar answered Sep 19 '22 14:09

Subin Sebastian