Java Reference
In-Depth Information
You can bookmark a position of a buffer by using the mark() method. When you call the mark() method, the
buffer stores the current value of its position as its mark value. You can set the position of a buffer to its previously
bookmarked value by using the reset() method. The buffer's mark is not defined when it is created. You must
call the reset() method on a buffer only when its mark is defined. Otherwise, the reset() method throws an
InvalidMarkException .
The following invariant must hold during the lifetime of a buffer:
0 <= mark <= position <= limit <= capacity
Since the capacity of a buffer never changes and mark has limited use through the mark() and reset() methods,
I will limit the discussion only to the position and limit properties of a buffer. There are some indirect consequences of
changing the position and limit values. Since the mark cannot be greater than the position, the mark is discarded if the
position is set less than the current mark value. If you set the limit less than the position, the position is automatically
set equal to the limit value.
So far, you have read a great deal on buffers. It's time to see a buffer in action. Listing 9-1 contains the code to
create a new buffer and display its four properties.
Listing 9-1. Mark, Position, Limit, and Capacity of a New Buffer
// BufferInfo.java
package com.jdojo.nio;
import java.nio.ByteBuffer;
import java.nio.InvalidMarkException;
public class BufferInfo {
public static void main(String[] args) {
// Create a byte buffer of capacity 8
ByteBuffer bb = ByteBuffer.allocate(8);
System.out.println("Capacity: " + bb.capacity());
System.out.println("Limit: " + bb.limit());
System.out.println("Position: " + bb.position());
// The mark is not set for a new buffer. Calling the
// reset() method throws a runtime exception if the mark is not set.
// If the mark is set, the position is set to the mark value.
try {
bb.reset();
System.out.println("Mark: " + bb.position());
}
catch (InvalidMarkException e) {
System.out.println("Mark is not set");
}
}
}
Capacity: 8
Limit: 8
Position: 0
Mark is not set
 
Search WWH ::




Custom Search