Java-Find Remaining Data

Find Remaining Data

The boolean method hasRemaining( ) will tell you if you’ve reached the buffer’s limit when reading. The following is a way to read elements from a buffer :

Alternatively, the remaining( ) method will tell you the number of elements that remain from the current position to the limit. You can use a loop like this to read the buffer :


If you have exclusive control of the buffer, this would be more efficient because the limit will not be checked (which requires invocation of an instance method on buffer) on every iteration of the loop. The first example above would allow for multiple threads to read elements from the buffer concurrently.



Program Source

import java.nio.ByteBuffer;

public class Javaapp {

    public static void main(String[] args) {

        ByteBuffer buf = ByteBuffer.allocate(12);
        byte by[] = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
        int total = buf.remaining();
        for(int i=0;i<total;i++) 
            System.out.print(buf.get() + ",");

Leave a Comment