tags:

views:

1191

answers:

1

I need to put the contents of a java.nio.ByteBuffer into an java.io.OutputStream. (wish I had a Channel instead but I don't) What's the best way to do this?

edit: and I can't use the ByteBuffer's array() method since it can be a read-only buffer.

edit 2: I also may be interspersing writes to the OutputStream between using this ByteBuffer and having a regular array of byte[] which I can with use OutputStream.write() directly.

+8  A: 

Look at Channels.newChannel(OutputStream) will give you a channel given an OutputStream. With the WritableByteChannel adapter you can provide the ByteBuffer which will write it to the OutputStream.

public void writeBuffer(ByteBuffer buffer, OutputStream stream) {
   WritableByteChannel channel = Channels.newChannel(stream);

   channel.write(buffer);
}

This should do the trick!

ng
if I keep the channel as well as the stream, can I intermix calls to both?
Jason S
Ya, sure can, reduces the cost of creating the channel every time :)
ng