Search code examples
javaserializationobjectoutputstreambytearrayoutputstream

How to serialize objects together with byte array into a file?


I have a java class that contains an inner class and a byte array member, for example KeyValPair hdr and byte[] content, and I'd like to serialize only the inner class hdr and the byte array content, rather than the whole class instance as there are some other unneccesary fields in the class.

I know how to serialize objects using ObjectOutputStream, and I know how to convert an object into a byte array, but I'm not sure whether I can store them at the same time without converting the inner class instanceKeyValPair hdr into byte array. If I convert it into byte array and store it together with content, how do I know the length of hdr when deserializing it from file?

Another question is that is it possible to use MappedBytesBuffer together with ObjectOutputStream or something like ByteArrayOutputStream? Because I'm in a scene that requires certain level of performance for I/O and the process might be killed... so is it a good idea to use MappedBytesBuffer?

I'm a newbie to java, so any help is appreciated.


Solution

  • Just serialize the byte array as an object, with writeObject() and deserialize with readObject(). That will take care of the length automatically.