Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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 :)

share|improve this question
add comment

1 Answer

up vote 1 down vote accepted

Whenever you read from or write to the buffer, only it's position changes.

So you are wrong about reading from channel. Note that reading from channel means writing to the buffer. You can set the position to 0 and limit - to the maximum number of bytes to read before you call Channel.read(ByteBuffer). The read operation then updates the position to the number of bytes actually read. So, to start reading from buffer you have to call ByteBuffer.flip().

share|improve this answer
    
so basically, nothing affects the limit variable –  Dummy Derp Sep 11 '12 at 13:27
1  
Right. The documentation states this as: "A buffer's limit is the index of the first element that should not be read or written." –  lorus Sep 11 '12 at 14:08
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.