Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put data from an OutputStream into a ByteBuffer?

Tags:

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?

like image 676
Rasto Avatar asked Apr 26 '10 20:04

Rasto


People also ask

How do you convert bytes to ByteBuffer?

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.

How do I allocate ByteBuffer?

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.

How do you write OutputStream to string?

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.


1 Answers

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.

like image 196
DJClayworth Avatar answered Jan 14 '23 13:01

DJClayworth