ByteBuffer compact() in Java

compact(): This method is available in java.nio.ByteBuffer class of Java.

Syntax:

ByteBuffer java.nio.ByteBuffer.compact()

This method compacts this buffer. The buffer's position is then set to n+1 and its limit is set to its capacity. The mark, if defined, is discarded. The buffer's position is set to the number of bytes copied, rather than to zero.

Parameters: NA

Returns: This buffer.

Throws:

ReadOnlyBufferException - If this buffer is read-only

Approach 1: When no exceptions.

Java

import java.nio.ByteBuffer;

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

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

        System.out.println(bb.compact());

    }
}

Output:

java.nio.HeapByteBuffer[pos=4 lim=4 cap=4]


Approach 2: ReadOnlyBufferException

Java

import java.nio.ByteBuffer;

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

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

        ByteBuffer readOnly = bb.asReadOnlyBuffer();
        System.out.println(readOnly.compact());

    }
}


Output:

Exception in thread "main" java.nio.ReadOnlyBufferException at java.base/java.nio.HeapByteBufferR.compact(HeapByteBufferR.java:296)


No comments:

Post a Comment