Java NIO Byte Buffer
Buffer is an encapsulation for array of bytes. This class provisions some useful methods to read/write data, and switch between read and write.
indicators
The Buffer class has a byte[]
inside to store actual data in byte format. There are several indices used to indicate possible read/write position. In all there are 4 variables, mark
, position
, limit
and capacity
The relative relationship between them are:
0 <= mark <= position <= limit <= capacity
capacity
It is the length of byte array, unchangeable at all.
limit
It is soft length of byte array. Meaning it is the length of byte that can read/write. Any data that beyond this limit is not readable/writeable.
position
It is the current location of data to read/write
mark
Just an interesting point where you may want to revisit after.
Usage
The basic usage is to instantiate a buffer by
1 |
|
write into buffer
1 |
|
read from buffer
1 |
|
That is the usage of buffer, remember you must switch between read
and write
mode by using flip
method, otherwise you will not be able to get what you want.