ByteBuffer class provides ‘wrap’ method, it wraps a byte
array into a buffer.
public static
ByteBuffer wrap(byte[] array)
public static
ByteBuffer wrap(byte[] array, int offset, int length)
Above methods wraps the byte array into a byte buffer.
The new buffer will be backed by the given byte array. That is Modifications to
the array will cause buffer to be modified and vice versa.
Find the below working application.
Test.java
package com.sample.app; import java.io.IOException; import java.nio.ByteBuffer; public class Test { private static void printMetaInfo(String message, ByteBuffer byteBuffer) { System.out.println(message); System.out.printf("Limit : %d\n", byteBuffer.limit()); System.out.printf("Capacity : %d\n", byteBuffer.capacity()); System.out.printf("Position : %d\n", byteBuffer.position()); } private static void printBuffer(String message, ByteBuffer byteBuffer) { System.out.println(message); for (int i = 0; i < byteBuffer.capacity(); i++) { System.out.println(byteBuffer.get(i)); } } public static void main(String... args) throws IOException { byte[] arr = { 64, 65, 66, 67, 68 }; ByteBuffer byteBuffer = ByteBuffer.wrap(arr); printMetaInfo("Meta information of byteBuffer", byteBuffer); printBuffer("\nElements of the byte buffer are", byteBuffer); } }
Output
Meta information of byteBuffer
Limit : 5
Capacity : 5
Position : 0
Elements of the byte buffer are
64
65
66
67
68
No comments:
Post a Comment