Buffer class provides hasRemaining method, it returns
true, if there is at least one element remaining in between the current
position and the limit of the buffer.
Below program uses 'hasRemaining' method to check whether
there is any elements in the buffer and print the element if any.
Test.java
package com.sample.nio; import java.nio.ByteBuffer; public class Test { public static void main(String args[]) throws Exception { ByteBuffer byteBuffer = ByteBuffer.allocate(5); /* Add elements to the buffer */ byteBuffer.put((byte) 'H'); byteBuffer.put((byte) 'E'); byteBuffer.put((byte) 'L'); byteBuffer.put((byte) 'L'); byteBuffer.put((byte) 'O'); byteBuffer.clear(); while (byteBuffer.hasRemaining()) { byte element = byteBuffer.get(); System.out.println("element : " + (char) element); } } }
Output
element : H
element : E
element : L
element : L
element : O
No comments:
Post a Comment