ByteBuffer compact() method in Java with Examples - GeeksforGeeks

06 Jun, 2021
The compact() method of java.nio.ByteBuffer class is used to compact the given buffer.The bytes between the buffer’s current position and its limit, if any, are copied to the beginning of the buffer. That is, the byte at index p = position() is copied to index zero, the byte at index p + 1 is copied to index one, and so forth until the byte at index limit() – 1 is copied to index n = limit() – 1 – p. 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, so that an invocation of this method can be followed immediately by an invocation of another relative put method.Invoke this method after writing data from a buffer in case the write was incomplete. Syntax :  
public abstract ByteBuffer compact()
Return Value: This method returns the new ByteBuffer with the same content as that of this buffer.Exception: This method throws the ReadOnlyBufferException, If this buffer is read-only.Below program illustrates the compact() method:Examples 1:  
Java
// Java program to demonstrate// compact() method import java.nio.*;import java.util.*; public class GFG {    public static void main(String[] args)    {         // Declaring the capacity of the ByteBuffer        int capacity = 7;         // Creating the ByteBuffer         // creating object of ByteBuffer        // and allocating size capacity        ByteBuffer bb = ByteBuffer.allocate(capacity);         // putting the int to byte typecast value in ByteBuffer        bb.put((byte)20);        bb.put((byte)30);        bb.put((byte)40);         // print the ByteBuffer        System.out.println("Original ByteBuffer: "                           + Arrays.toString(bb.array()));         System.out.println("Position: " + bb.position());         System.out.println("limit: " + bb.limit());         // Creating a compacted  ByteBuffer of same ByteBuffer        // using compact() method        ByteBuffer cbb = bb.compact();         // print the ByteBuffer        System.out.println("\nCompacted ByteBuffer: "                           + Arrays.toString(cbb.array()));         System.out.println("Position: " + cbb.position());         System.out.println("limit: " + cbb.limit());         // putting the int to byte typecast value in compacted ByteBuffer        cbb.put((byte)50);         // print the ByteBuffer        System.out.println("\nUpdated Compacted ByteBuffer: "                           + Arrays.toString(cbb.array()));        System.out.println("Position: " + cbb.position());        System.out.println("limit: " + cbb.limit());    }}
Original ByteBuffer: [20, 30, 40, 0, 0, 0, 0]
Position: 3
limit: 7

Compacted ByteBuffer: [0, 0, 0, 0, 0, 0, 0]
Position: 4
limit: 7

Updated Compacted ByteBuffer: [0, 0, 0, 0, 50, 0, 0]
Position: 5
limit: 7
 
Examples 2:  
Java
// Java program to demonstrate// compact() method import java.nio.*;import java.util.*; public class GFG {    public static void main(String[] args)    {         // Declaring the capacity of the ByteBuffer        int capacity = 5;         // Creating the ByteBuffer        try {             // creating object of ByteBuffer            // and allocating size capacity            ByteBuffer bb = ByteBuffer.allocate(capacity);             // putting the int to byte typecast value in ByteBuffer            bb.put((byte)20);            bb.put((byte)30);            bb.put((byte)40);            bb.rewind();             // Creating a read-only copy of ByteBuffer            // using asReadOnlyBuffer() method            ByteBuffer bb1 = bb.asReadOnlyBuffer();             // print the ReadOnlyBuffer            System.out.print("ReadOnlyBuffer ByteBuffer: ");            while (bb1.hasRemaining())                System.out.print(bb1.get() + ", ");            System.out.println("");             // print the Position of ByteBuffer bb            System.out.println("\nPosition: " + bb.position());             // print the Limit of ByteBuffer bb            System.out.println("\nlimit: " + bb.limit());             // Creating a compacted  ByteBuffer of same ReadOnlyBuffer            // using compact() method            System.out.println("\nTrying to compact the ReadOnlyBuffer bb1");            ByteBuffer rbb = bb1.compact();        }         catch (IllegalArgumentException e) {             System.out.println("Exception throws " + e);        }         catch (ReadOnlyBufferException e) {             System.out.println("Exception throws " + e);        }    }}
ReadOnlyBuffer ByteBuffer: 20, 30, 40, 0, 0, 

Position: 0

limit: 5

Trying to compact the ReadOnlyBuffer bb1
Exception throws java.nio.ReadOnlyBufferException
 
anikakapoor
Java-ByteBuffer
Java-Functions
Java-NIO package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Functional Interfaces in Java
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions in Java
Generics in Java
Comparator Interface in Java with Examples
Strings in Java
How to remove an element from ArrayList in Java?
Difference between Abstract Class and Interface in Java