Java Reference
In-Depth Information
put(byte[] source)
: It is the same as calling
put(byte[] source, 0, source.length)
.
•
ByteBuffer put(ByteBuffer src)
: It reads the remaining bytes from the specified byte
buffer
src
and writes them to the buffer. If the remaining space in the target buffer is less than
the remaining bytes in the source buffer, a runtime
BufferOverflowException
is thrown.
•
Let's have some pictorial views of the state of a buffer and its properties after each read and write. Figure
9-3
through
9-6
depict how the position of a buffer with a capacity of 8 is advanced after each write in the buffer. After the
eighth write in the buffer, the position and the limit become equal. If you attempt to write a ninth time, you would get
a
BufferOverflowException
. Note that I have used a relative write using the
put(byte b)
method.
0
0
0
0
0
0
0
0
Buffer Elements >>
Element's Index >>
012345678
P
L
Figure 9-3.
Buffer state with capacity 8 after creation. Buffer state - (position=0, limit=8)
50
0
0
0
0
0
0
0
Buffer Elements >>
012345678
P
Element's Index >>
L
Figure 9-4.
Buffer state after calling put((byte)50). Buffer state - (position= 1, limit=8)
50
51
0
0
0
0
0
0
Buffer Elements >>
012345678
P
Element's Index >>
L
Figure 9-5.
Buffer state after calling put((byte)51). Buffer state - (position= 2, limit=8)
50
51
52
53
54
55
56
57
Buffer Elements >>
012345678
Element's Index >>
L
P
Figure 9-6.
Buffer state after calling put((byte)52), put((byte)53), put((byte)54), put((byte)55), put((byte)56), and
put((byte)57). Buffer state - (position= 8, limit=8)
Let's read the data that you have just written into the buffer whose state is shown in Figure
9-6
. Note that the
position of the buffer is 8 and its limit is also 8. If you call the
get()
method (a relative read) to read data from this
buffer, you would get a
BufferUnderflowException
. You have just filled the buffer with data. However, when you
attempt to read the data, you get an exception because the
get()
method returns data from the current position of
the buffer, which is out of range in this case. The
get()
method will return data only if the position of the buffer is in
the range of 0 and 7. Let's not lose hope, and try to read the data using an absolute position with the
get(int index)
method. If you call
get(0), get(1) ... get(7)
, you will be surprised to know that you can read all the data you had
written. Listing 9-2 demonstrates this.