How to put data from an OutputStream into a ByteBuffer?

Rasto picture Rasto · Apr 26, 2010 · Viewed 34.3k times · Source

In Java I need to put content from an OutputStream (I fill data to that stream myself) into a ByteBuffer. How to do it in a simple way?

Answer

DJClayworth picture DJClayworth · Apr 26, 2010

You can create a ByteArrayOutputStream and write to it, and extract the contents as a byte[] using toByteArray(). Then ByteBuffer.wrap(byte []) will create a ByteBuffer with the contents of the output byte array.