put(int , byte[]): This method is available in java.nio.ByteBuffer class of Java.
Syntax:
ByteBuffer java.nio.ByteBuffer.put(int index, byte[] src)
This method takes two arguments one of type int and another of type byte array as its parameters. This method copies bytes into this buffer from the given source array. The position of this buffer is unchanged.
Parameters: Two parameters are required for this method.
index: The index in this buffer at which the first byte will be written; must be non-negative and less than limit().
src: The array from which bytes are to be read.
Returns: This buffer.
Throws:
1. IndexOutOfBoundsException - If index is negative, not smaller than limit(),or limit() - index < src.length.
2. ReadOnlyBufferException - If this buffer is read-only.
Approach 1: When no exceptions.
Java
import java.nio.ByteBuffer;import java.util.Arrays;public class ByteBufferput5 {public static void main(String[] args) {byte array[] = { 1, 2, 3, 4, 10, 24, 45, 78 };ByteBuffer bb = ByteBuffer.wrap(array);int index = 2;byte src[] = { 78, 100, 120, 76 };System.out.println(Arrays.toString(bb.put(index, src).array()));}}
Output:
[1, 2, 78, 100, 120, 76, 45, 78]
Approach 2: IndexOutOfBoundsException
Java
import java.nio.ByteBuffer;import java.util.Arrays;public class ByteBufferput5 {public static void main(String[] args) {byte array[] = { 1, 2, 3, 4, 10, 24, 45, 78 };ByteBuffer bb = ByteBuffer.wrap(array);int index = 6;byte src[] = { 78, 100, 120, 76 };System.out.println(Arrays.toString(bb.put(index, src).array()));}}
Output:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Range [6, 6 + 4) out of bounds for length 8 at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64) at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckFromIndexSize(Preconditions.java:82) at java.base/jdk.internal.util.Preconditions.checkFromIndexSize(Preconditions.java:343) at java.base/java.util.Objects.checkFromIndexSize(Objects.java:411) at java.base/java.nio.HeapByteBuffer.put(HeapByteBuffer.java:257) at java.base/java.nio.ByteBuffer.put(ByteBuffer.java:1189)
Approach 3: ReadOnlyBufferException
Java
import java.nio.ByteBuffer;import java.util.Arrays;public class ByteBufferput5 {public static void main(String[] args) {byte array[] = { 1, 2, 3, 4, 10, 24, 45, 78 };ByteBuffer bb = ByteBuffer.wrap(array);ByteBuffer readOnly = bb.asReadOnlyBuffer();int index = 2;byte src[] = { 78, 100, 120, 76 };System.out.println(Arrays.toString(readOnly.put(index, src).array()));}}
Output:
Exception in thread "main" java.nio.ReadOnlyBufferException at java.base/java.nio.HeapByteBufferR.put(HeapByteBufferR.java:262) at java.base/java.nio.ByteBuffer.put(ByteBuffer.java:1189)
No comments:
Post a Comment