Java Reference
In-Depth Information
However, if there's a chance your buffer might contain less data than you have allocated,
you should call the buffer's flip() method after reading data into the buffer. This sets
the current position to the start of the data you just read and sets the limit to the end.
Later today, you'll use a byte buffer to store data loaded from a web page on the Internet.
This is a place where flip() becomes necessary because you don't know how much
data the page contains when you request it.
If the buffer is 1,024 bytes in size and the page contains 1,500 bytes, the first attempt to
read data loads the buffer with 1,024 bytes, filling it.
The second attempt to read data loads the buffer with only 476 bytes, leaving the rest
empty. If you call flip() afterward, the current position is set to the beginning of the
buffer, and the limit is set to 476.
The following code creates an array of Fahrenheit temperatures, converts them to
Celsius, and then stores the Celsius values in a buffer:
17
int[] temps = { 90, 85, 87, 78, 80, 75, 70, 79, 85, 92, 99 };
IntBuffer tempBuffer = IntBuffer.allocate(temperatures.length);
for (int i = 0; i < temps.length; i++) {
float celsius = ( (float)temps[i] - 32 ) / 9 * 5;
tempBuffer.put( (int)celsius );
};
tempBuffer.position(0);
for (int i = 0; tempBuffer.remaining() > 0; i++)
System.out.println(tempBuffer.get());
After the buffer's position is set back to the start, the contents of the buffer are displayed.
Byte Buffers
You can use the buffer methods introduced so far with byte buffers, but byte buffers also
offer additional useful methods.
For starters, byte buffers have methods to store and retrieve data that isn't a byte:
putChar( char ) —Stores 2 bytes in the buffer that represent the specified char
value
n
putDouble( double ) —Stores 8 bytes in the buffer that represent a double value
n
putFloat( float ) —Stores 4 bytes in the buffer that represent a float value
n
putInt( int ) —Stores 4 bytes in the buffer that represent an int value
n
putLong( long ) —Stores 8 bytes in the buffer that represent a long value
n
putShort( short ) —Stores 2 bytes in the buffer that represent a short value
n
Search WWH ::




Custom Search