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?
In short, to make a conversion between a ByteBuffer and a byte array you should: Create a byte array and wrap it into a ByteBuffer. The buffer's capacity and limit will be the array's length and its position will be zero. Retrieve the bytes between the current position and the limit of the buffer.
A new ByteBuffer can be allocated using the method allocate() in the class java. nio. ByteBuffer. This method requires a single parameter i.e. the capacity of the buffer.
Example: Convert OutputStream to String This is done using stream's write() method. Then, we simply convert the OutputStream to finalString using String 's constructor which takes byte array. For this, we use stream's toByteArray() method.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With