Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Iterating over a jdk ByteBuffer
public final class ByteBufIterator {
public static void main(String[] args) {
ByteBuffer buffer = ByteBuffer.allocate(Integer.BYTES * 10);
for (int i = 0; i < 10; i++) buffer.putInt(i);
buffer.flip(); // dont forget to flip!!!
// read in groups of 3
// so 4 BBs, 3 of size 3 and 1 of 1
final int end = buffer.limit(), stride = 3 * Integer.BYTES;
for (int start = 0; start != end; start = buffer.limit()) {
int delta = Math.min(end - start, stride);
buffer.position(start).limit(start + delta);
consume(buffer.asReadOnlyBuffer());
}
}
private static void consume(ByteBuffer buffer) {
System.out.println(state(buffer));
while (buffer.hasRemaining()) System.out.print(buffer.getInt() + " ");
System.out.println();
}
public static String state(ByteBuffer bb) {
return String.format("direct: %s, position: %,d, limit: %,d, capacity: %,d",
bb.isDirect(), bb.position(), bb.limit(), bb.capacity());
}
}
// Result is as follows:
// direct: false, position: 0, limit: 12, capacity: 40
// 0 1 2
// direct: false, position: 12, limit: 24, capacity: 40
// 3 4 5
// direct: false, position: 24, limit: 36, capacity: 40
// 6 7 8
// direct: false, position: 36, limit: 40, capacity: 40
// 9
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.