java.nio.Buffer Class in Java - GeeksforGeeks

03 Feb, 2022
The Buffer class provides a buffer or a container for data chunks of specific primitive types. A finite sequence of elements is stored linearly in a buffer.
Important properties of a buffer that make it convenient to perform read and write operations in the data are:
Capacity: This property determines the maximum number of elements that can be there in a buffer.
Limit: This property determines the limit of the data that can be read or write by providing the index of the elements.
Position: This property determines the location of the current element in the buffer.
Syntax: Class declaration
public abstract class Buffer extends Object
Buffer class provides a subclass for each of the following buffer data types such as ByteBuffer, MappedByteBuffer, CharBuffer, DoubleBuffer, FloatBuffer, IntBuffer, LongBuffer, ShortBuffer. Buffer class inherits the following methods from class java.lang.Object such as clone(), finalize(), getClass(), hashCode(), notify(), notifyAll(), toString(), wait(). Now, moving on to the methods of Buffer class is as follows as shown alphabetically in the tabular format shown below:
Implementation: Buffer class and its methods
Example 1
Java
// Java program to demonstrate Buffer Class // Importing required librariesimport java.nio.*;import java.util.*; // Main classpublic class GFG {     // Main driver method    public static void main(String[] args)    {        // Declaring the capacity of the ByteBuffer        int capacity = 5;         // Try block to check for exceptions        try {             // Creating the ByteBuffer             // Creating object of ByteBuffer class and            // allocating size capacity            ByteBuffer bufferObj                = ByteBuffer.allocate(capacity);             // Putting the int to byte typecast            // value in ByteBuffer using put() method             // Custom input entries            bufferObj.put((byte)10);            bufferObj.put((byte)20);            bufferObj.put((byte)30);            bufferObj.put((byte)40);            bufferObj.put((byte)50);             // Typecasting ByteBuffer into Buffer            Buffer bufferObj1 = (Buffer)bufferObj;             // Getting array that backs this buffer            // using array() method            byte[] arr = (byte[])bufferObj1.array();             // Display message only            System.out.print(" The array is : [");             // Print the array            for (int i = 0; i < arr.length; i++)                System.out.print(" " + arr[i]);            System.out.print(" ]");        }         // Catch block to handle the exception        catch (ReadOnlyBufferException e) {             // Print message where exception occurred            // is displayed on console            System.out.println("Exception throws: " + e);        }    }}
 The array is : [ 10 20 30 40 50 ]
Example 2
Java
// Java program to demonstrate Buffer class // Importing required librariesimport java.nio.*;import java.util.*; // Main classpublic class GFG {     // Main driver method    public static void main(String[] args)    {         // try block to check for exceptions        try {             // Creating and initializing byte array            // with custom elements            byte[] barr = { 10, 20, 30, 40, 50 };             // Creating object of ByteBuffer class            // and allocating size capacity            ByteBuffer bufferObj = ByteBuffer.wrap(barr);             // Typecasting ByteBuffer into Buffer            Buffer bufferObj1 = (Buffer)bufferObj;             // now trying to set the position at index 2            bufferObj1.position(2);             // Setting this buffer mark position            // using mark() method            bufferObj1.mark();             // Again trying to set the position at index 4            bufferObj1.position(5);             // Display the position            System.out.println("position before reset: "                               + bufferObj1.position());             // Now trying to call clear() to restore            // to the position at index 0 by discarding the            // mark            bufferObj1.clear();             // Print and display the position            System.out.println("position after reset: "                               + bufferObj1.position());        }         // Catch block to handle the exception        catch (InvalidMarkException e) {             // Display message to be showcase when exception            // occurred            System.out.println(                "new position is less than "                + "the position we marked before ");             // Print the exception on the console            // along with display message            System.out.println("Exception throws: " + e);        }    }}
position before reset: 5
position after reset: 0
 
anikakapoor
adnanirshad158
sumitgumber28
Java-Buffer
Java-Classes
Java-NIO package
Picked
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
Internal Working of HashMap in Java
Strings in Java