Java Reference
In-Depth Information
50
51
52
53
54
0
0
0
Buffer Elements >>
Element's Index >>
012345678
P
M
L
Figure 9-11. Buffer's state before calling its reset() method
50
51
52
53
54
0
0
0
Buffer Elements >>
012345678
Element's Index >>
M
L
P
Figure 9-12. Buffer's state after calling its reset() method
The rewind() method sets the position of the buffer to zero and discards its mark. It does not affect the limit.
Typically, you call this method between multiple read/write operations to use the same number of data elements in
the buffer multiple times. Figure 9-13 and 9-14 show the state of a buffer before and after calling its rewind() method.
50
51
52
53
54
0
0
0
Buffer Elements >>
Element's Index >>
012345678
P
L
Figure 9-13. Buffer's state before calling its rewind() method
50
51
52
53
54
0
0
0
Buffer Elements >>
012345678
P
Element's Index >>
L
Figure 9-14. Buffer's state after calling its rewind() method
Read-Only Buffers
A buffer can be read-only or read-write. You can only read the contents of a read-only buffer. Any attempt to change
the contents of a read-only buffer results in a ReadOnlyBufferException . Note that the properties of a read-only
buffer such as its position, limit, and mark can be changed during the read operations, but not its data.
You may want to get a read-only buffer from a read-write buffer, so you can pass it as an argument to a method to
make sure the method does not modify its contents. You can get a read-only buffer by calling the asReadOnlyBuffer()
method of the specific buffer class. You can check if a buffer is read-only by calling the isReadOnly() method as
follows:
// Create a buffer that is read-write by default
ByteBuffer bb = ByteBuffer.allocate(1024);
boolean readOnly = bb.isReadOnly(); // Assigns false to readOnly
 
 
Search WWH ::




Custom Search