ByteBuffer put(byte[]) in Java

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

Syntax:

ByteBuffer java.nio.ByteBuffer.put(byte[] src)

This method takes one argument of type byte array as its parameter. This method transfers the entire content of the given source byte array into this buffer.

Parameters: One parameter is required for this method.

src: The source array.

Returns: This buffer.

Throws:

1. BufferOverflowException - If there is insufficient space in this buffer.

2. ReadOnlyBufferException - If this buffer is read-only.

Approach 1: When no exceptions.

Java

import java.nio.ByteBuffer;
import java.util.Arrays;

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

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

        byte src[] = { 304060708090 };
        System.out.println(Arrays.toString(bb.put(src).array()));

    }
}

Output:

[30, 40, 60, 70, 80, 90, 7, 7, 8, 9]


Approach 2: BufferOverflowException

Java

import java.nio.ByteBuffer;
import java.util.Arrays;

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

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

        byte src[] = { 304060708090 };
        System.out.println(Arrays.toString(bb.put(src).array()));

    }
}


Output:

Exception in thread "main" java.nio.BufferOverflowException at java.base/java.nio.HeapByteBuffer.put(HeapByteBuffer.java:235) at java.base/java.nio.ByteBuffer.put(ByteBuffer.java:1100)


Approach 3: ReadOnlyBufferException 

Java

import java.nio.ByteBuffer;
import java.util.Arrays;

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

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

        ByteBuffer readOnly = bb.asReadOnlyBuffer();

        byte src[] = { 304060708090 };
        System.out.println(Arrays.toString(readOnly.put(src).array()));

    }
}


Output:

Exception in thread "main" java.nio.ReadOnlyBufferException at java.base/java.nio.HeapByteBufferR.put(HeapByteBufferR.java:240) at java.base/java.nio.ByteBuffer.put(ByteBuffer.java:1100)


No comments:

Post a Comment