'rewind()' method is used to re-read the data. When you
call the rewind() method on buffer instance, it resets the current position to 0
and set the mark to undefined state (mark=-1).
Test.java
package com.sample.nio; import java.nio.ByteBuffer; public class Test { private static final String ALPHABETS = "abcdefghijklmnopqrstuvwxyz"; private static void printStats(ByteBuffer byteBuffer) { int currentPosition = byteBuffer.position(); int activeElePosition = byteBuffer.limit(); System.out.println("position : " + currentPosition + ", limit : " + activeElePosition); System.out.println("\n"); } public static void main(String args[]) throws Exception { /* Define new byte buffer of capacity 11 */ ByteBuffer byteBuffer = ByteBuffer.allocate(26); System.out.println("Before inserting the data into buffer"); printStats(byteBuffer); for (int i = 0; i < ALPHABETS.length(); i++) { byteBuffer.put((byte) ALPHABETS.charAt(i)); } System.out.println("After inserting 26 characters into the buffer"); printStats(byteBuffer); byteBuffer.rewind(); System.out.println("After calling rewind() api on the buffer"); printStats(byteBuffer); } }
Output
Before inserting the data into buffer position : 0, limit : 26 After inserting 26 characters into the buffer position : 26, limit : 26 After calling rewind() api on the buffer position : 0, limit : 26
No comments:
Post a Comment