Search this site
What do you think of this article? Did it help you? Found a mistake? Feedback and suggestions here
The ByteBuffer is the most generic and commonly used NIO buffer class.
How to create a ByteBuffer
As mentioned in our discussion of buffer layout, a buffer class is generally "wrapped" around an underlying byte array. Modifying or reading from the buffer then accesses the underlying array and vice versa. If we have a byte array, we can create a buffer object around it by calling the ByteBuffer.wrap() method:
byte ba = ... ByteBuffer buff = ByteArray.wrap(ba);
A less commonly used variant of wrap() allows us to wrap around a part of an array.
If we just want to create a brand new byte array and buffer object all in one go, we can call the convenience method ByteBuffer.allocate() method, passing the required buffer and array size (in bytes):
ByteBuffer buff = ByteArray.allocate(100);
Position and limit of the buffer
Recall from our overview of the layout of a buffer that a ByteBuffer (and other types of buffer) has a current position and limit. When a new buffer is created:
In other words, a newly created buffer is set up to sequentially read or write over the entire buffer from start to finish, unless we manually change the position and/or limit.
Reading and writing
On the next page, we'll look at the methods to read and write data to the ByteBuffer.
Written by Neil Coffey. Copyright © Javamex UK 2012. All rights reserved.