Search code examples
javaserializationniobytebuffer

Could ByteBuffer implement DataOutput/DataInput?


Is there some subtle reason why java.nio.ByteBuffer does not implement java.io.DataOutput or java.io.DataInput, or did the authors just not choose to do this? It would seem straightforward to map the calls (e.g. putInt() -> writeInt()).

The basic problem I (and some others, apparently) have is older classes which know how to serialize/serialize themselves using the generic interfaces: DataInput/DataOutput. I would like to reuse my custom serialization without writing a custom proxy for ByteBuffer.


Solution

  • Just wrap the buffer in ByteArrayInputStream or ByteArrayOutputStream using the put() or wrap() methods. The problem with having a ByteBuffer directly emulate a datainput/output stream has to do with not knowing the sizes in advance. What if there's an overrun?

    What is needed is a ByteBufferOutputStream in which you can wrap / expose the required behaviors. Examples of this exist; the Apache avro serialization scheme has such a thing. It's not too hard to roll your own. Why is there not one by default? Well, it's not a perfect world...

    ByteArrayOutputStream backing = new ByteArrayOutputStream();
    DataOutput foo = new DataOutputStream(backing); 
    // do your serialization out to foo
    
    foo.close();
    ByteBuffer buffer = ByteBuffer.wrap(backing.toByteArray());
    // now you've got a bytebuffer...