14

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.

Community
  • 1
  • 1
Steve
  • 4,935
  • 11
  • 56
  • 83

3 Answers3

32

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();
Subin Sebastian
  • 10,870
  • 3
  • 37
  • 42
  • This is closed so not sure whether people can read it or not. But let's test the power of stackoverflow: when I implements Serializable interface, I am supposed to provide a serialVersionID, which should be a UID. The question is, whether I am supposed to provide it or fine to leave it out. If I am supposed to provide it, how? Any UID is fine? – Steve Jan 03 '13 at 21:52
2

Make the Author class serializable and write the list to an ObjectOutputStream backed by a ByteArrayOutputStream.

Henry
  • 42,982
  • 7
  • 68
  • 84
1

Make your class Serializable; create an ObjectStream over a ByteStream and write your list to the ObjectStream. Pass the byte buffer from the ByteStream to your caching API.

When retrieving from the cache, you reverse the process. Create a ByteStream from the byte[] returned by the caching API; create an ObjectStream from the ByteStream; read your collection from the ObjectStream.

antlersoft
  • 14,636
  • 4
  • 35
  • 55