Java Reference
In-Depth Information
In the previous snippet of code, you used a for-loop to read the data from the buffer. The index of the for-loop
runs from zero to limit -1. However, there is an easier way to read/write data from/to a buffer using relative read/
write method. The hasRemaining() method of a buffer returns true if you can use relative get() or put() method on
the buffer to read/write at least one element. You can also get the maximum number of elements you can read/write
using relative get() or put() methods by using its remaining() method. Listing 9-3 demonstrates the use of these
methods.
Listing 9-3. Using the flip() and hasRemaining() Methods of a Buffer Between Relative Reads and Writes
// BufferReadWriteRelativeOnly.java
package com.jdojo.nio;
import java.nio.ByteBuffer;
public class BufferReadWriteRelativeOnly {
public static void main(String[] args) {
// Create a byte buffer of capacity 8
ByteBuffer bb = ByteBuffer.allocate(8);
// Print the buffer info
System.out.println("After creation:");
printBufferInfo(bb);
// Must call flip() to reset the position to zero because
// the printBufferInfo() method uses relative get() method,
// which increments the position
bb.flip();
// Populate buffer elements from 50 to 57
int i = 50;
while (bb.hasRemaining()) {
bb.put((byte)i++);
}
// Call flip() again to reset the position to zero,
// because the above put() call incremented the position
bb.flip();
// Print the buffer info
System.out.println("After populating data:");
printBufferInfo(bb);
}
public static void printBufferInfo(ByteBuffer bb) {
int limit = bb.limit();
System.out.println("Position = " + bb.position() +
", Limit = " + limit);
 
Search WWH ::




Custom Search