ByteBuffer compact() method in Java with Examples

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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 typcast 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());
    }
}

chevron_right


Output:

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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);
        }
    }
}

chevron_right


Output:

ReadOnlyBuffer ByteBuffer: 20, 30, 40, 0, 0, 

Position: 0

limit: 5

Trying to compact the ReadOnlyBuffer bb1
Exception throws java.nio.ReadOnlyBufferException


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.