ByteBuffer get(byte[]) in Java

get(byte[]): This method is available in java.nio.ByteBuffer class of Java.

Syntax:

ByteBuffer java.nio.ByteBuffer.get(byte[] dst)

This method takes one argument of type byte array as its parameter. This method transfers bytes from this buffer into the given destination array.

Parameters: One parameter is required for this method.

dst: The destination array.

Returns: This buffer.

Throws:

BufferUnderflowException - If there are fewer than length bytes remaining in this buffer

Approach 1: When no exceptions.

Java

import java.nio.ByteBuffer;

public class ByteBufferget2 {
    public static void main(String[] args) {

        byte array[] = { 123410178978 };
        ByteBuffer bb = ByteBuffer.wrap(array);

        byte dst[] = { 1034567890 };
        System.out.println(bb.get(dst));

    }
}

Output:

java.nio.HeapByteBuffer[pos=5 lim=8 cap=8]


Approach 2: BufferUnderflowException 

Java

import java.nio.ByteBuffer;

public class ByteBufferget2 {
    public static void main(String[] args) {

        byte array[] = { 1234 };
        ByteBuffer bb = ByteBuffer.wrap(array);

        byte dst[] = { 1034567890 };
        System.out.println(bb.get(dst));

    }
}


Output:

Exception in thread "main" java.nio.BufferUnderflowException at java.base/java.nio.HeapByteBuffer.get(HeapByteBuffer.java:185) at java.base/java.nio.ByteBuffer.get(ByteBuffer.java:814)


No comments:

Post a Comment