Java Reference
In-Depth Information
The working range for a relative read/write is the indices between position and limit - 1 of the buffer, where
position is less than limit -1. That is, you can read/write data using the relative get() and put() methods if the
position of the buffer is less than its limit.
The working range for the absolute read/write is the index between zero and limit -1. So, how do you read all
the data from a buffer using a relative position read, after you have finished writing data into the buffer? One way to
accomplish this is to set the limit of the buffer equal to its position and set its position to 0. The following snippet of
code shows this technique:
// Create a byte buffer of capacity 8 and populate its elements
ByteBuffer bb = ByteBuffer.allocate(8);
for(int i = 50; i < 58; i++) {
bb.put((byte)i);
}
// Set the limit the same as the position and set the position to 0
bb.limit(bb.position());
bb.position(0);
// Now bb is set to read all data using relative get() method
int limit = bb.limit();
for(int i = 0; i < limit; i++) {
byte b = bb.get(); // Uses a relative read
System.out.println(b);
}
The Buffer class has a method to accomplish just what you have coded in the above snippet of code. You can set
the limit of the buffer to its position and set the position to 0 by using its flip() method. Figure 9-7 shows the state
of a buffer, which has capacity of 8, after it has been created and after its two elements at index 0 and 1 have been
written. Figure 9-8 shows the state of the buffer after its flip() method is called. The flip() method discards the
mark of a buffer if it is defined.
50
51
0
0
0
0
0
0
Buffer Elements >>
Element's Index >>
012345678
P
L
Figure 9-7. Buffer's state just after you have written two elements at indexes 0 and 1
50
51
0
0
0
0
0
0
Buffer Elements >>
Element's Index >>
012345678
P
L
Figure 9-8. Buffer's state after writing two elements at indexes 0 and 1 and calling the flip() method
 
 
Search WWH ::




Custom Search