Java Reference
In-Depth Information
Wrapping
If you already have an array of data that you want to output, you'll normally wrap a
buffer around it, rather than allocating a new buffer and copying its components into
the buffer one at a time. For example:
byte [] data = "Some data" . getBytes ( "UTF-8" );
ByteBuffer buffer1 = ByteBuffer . wrap ( data );
char [] text = "Some text" . toCharArray ();
CharBuffer buffer2 = CharBuffer . wrap ( text );
Here, the buffer contains a reference to the array, which serves as its backing array.
Buffers created by wrapping are never direct. Again, changes to the array are reflected
in the buffer and vice versa, so don't wrap the array until you're finished with it.
Filling and Draining
Buffers are designed for sequential access. Recall that each buffer has a curent position
identified by the position() method that is somewhere between zero and the number
of elements in the buffer, inclusive. The buffer's position is incremented by one when
an element is read from or written to the buffer. For example, suppose you allocate a
CharBuffer with capacity 12, and fill it by putting five characters into it:
CharBuffer buffer = CharBuffer . allocate ( 12 );
buffer . put ( 'H' );
buffer . put ( 'e' );
buffer . put ( 'l' );
buffer . put ( 'l' );
buffer . put ( 'o' );
The position of the buffer is now 5. This is called filling the buffer.
You can only fill the buffer up to its capacity. If you tried to fill it past its initially set
capacity, the put() method would throw a BufferOverflowException .
If you now tried to get() from the buffer, you'd get the null character (\u0000) that Java
initializes char buffers with that's found at position 5. Before you can read the data you
wrote in out again, you need to flip the buffer:
buffer . flip ();
This sets the limit to the position (5 in this example) and resets the position to 0, the
start of the buffer. Now you can drain it into a new string:
String result = "" ;
while ( buffer . hasRemaining ()) {
result += buffer . get ();
}
Each call to get() moves the position forward one. When the position reaches the limit,
hasRemaining() returns false. This is called draining the buffer.
Search WWH ::




Custom Search