Basic Usage - Creating a ByteBuffer

suggest change

There are two ways to create a ByteBuffer, and one of them has a direct-memory variant.

If you already have a byte[], wrap it:

byte[] reqBuffer = new byte[BUFFER_SIZE];
int readBytes = socketInputStream.read(reqBuffer);
// read returns -1 at end of stream and may fill only part of the array
final ByteBuffer reqBufferWrapper = ByteBuffer.wrap(
        reqBuffer, 0, Math.max(readBytes, 0));

This would be a possibility for code that handles low-level networking interactions


If you do not have an already existing byte[], you can create a ByteBuffer over an array that’s specifically allocated for the buffer like this:

final ByteBuffer respBuffer = ByteBuffer.allocate(RESPONSE_BUFFER_SIZE);
putResponseData(respBuffer);
// assumes putResponseData writes at position 0 and leaves position at the end
socketOutputStream.write(respBuffer.array(), 0, respBuffer.position());

If the code-path is extremely performance critical and you need direct system memory access, the ByteBuffer can even allocate direct buffers using #allocateDirect()

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents