Java Reference
In-Depth Information
The ByteBuffer class has some extra methods that enable you to transfer binary data of other
primitive types to the buffer. For instance, you can transfer a value of type double to the buffer with
either of the following methods:
Method
Description
putDouble(double value)
Transfers the double value specified by the
argument to the buffer at the current position and
increments the position by 8. If there are less than 8
bytes remaining in the buffer, an exception of type
BufferOverflowException will be thrown.
putDouble(int index,
double value)
Transfers the double value specified by the second
argument, to the buffer starting at the index
position specified by the first argument. The
buffer's position will be unchanged. If there are less
than 8 bytes remaining in the buffer, an exception
of type BufferOverflowException will be
thrown. If index is negative or the buffer's limit is
less than or equal to index+7 , an exception of type
IndexOutOfBoundsException will be thrown.
There are similar pairs of methods defined in the ByteBuffer class to transfer elements of other basic
types. These are putChar() , putShort() , putInt() , putLong() , and putFloat() , each of
which transfers a value of the corresponding type. Like the other put() methods we have seen, these
all return a reference to the buffer for which they are called. This is to enable you to chain the calls for
these methods together in a single statement if you wish. For instance:
ByteBuffer buf = ByteBuffer.allocate(50);
String text = "Value of e";
buf.put(text.getBytes()).putDouble(Math.E);
Here, we write the string to the buffer by converting it to bytes by calling its getBytes() method, and
passing the result to the put() method for the buffer. The put() method returns a reference to the buffer,
buf , so we use that to call the putDouble() method to write the 8 bytes for the double value, Math.E , to
the buffer. The buffer will then contain a total of 18 bytes. Of course, putDouble() also returns a reference
to buf , so we could chain further calls together in the same statement if we so wished.
Note that we are transferring the string characters to the buffer as bytes in the local character encoding,
not as Unicode characters. To transfer them as the original Unicode characters, we could code the
operations like this:
char[] array = text.toCharArray(); // Create char[] array from the string
// Now use a loop to transfer array elements one at a time
for (int i = 0 ; i< array.length ; i++) {
buf.put(array[i]);
}
buf.putDouble(Math.E); // Transfer the binary double value
Search WWH ::




Custom Search