How are Java ByteBuffer's limit and position variable's updated?

Posted by Dummy Derp on Programmers See other posts from Programmers or by Dummy Derp
Published on 2012-09-11T03:26:19Z Indexed on 2012/09/11 3:49 UTC
Read the original article Hit count: 288

Filed under:
|
|
|

There are two scenarios: writing and reading
Writing:
Whenever I write something to the ByteBuffer by calling its put(byte[]) method the position variable is incremented as: current position + size of byte[] and limit stays at the max.
If, however, I put the data in a view buffer then I will have to, manually, calculate and update the position
Before I call the write(ByteBuffer) method of the channel to write something, I will have to flip() the Bytebuffer so that
position points to zero and limit points to the last byte that was written to the ByteBuffer.
Reading:
Whenever I call the read(ByteBuffer) method of a channel to read something, the position variable stays at 0 and the limit variable of the ByteBuffer points to the last byte that was read. So, if the ByteBuffer is smaller than the file being read, the limit variable is pushed to max
This means that the ByteBuffer is already flipped and I can proceed to extracting the values from the ByteBuffer.
Please, correct me where I am wrong :)

© Programmers or respective owner

Related posts about java

Related posts about file-handling