java.nio.Buffer Class in Java
Last Updated :
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:
Method | Description |
---|
array() | This method returns the array that backs this buffer |
arrayOffset() | This method returns the offset within this buffer's backing array of the first element of the buffer |
capacity() | This method returns this buffer's capacity. |
clear() | This method clears this buffer. |
flip() | This method flips this buffer. |
hasArray() | This method tells whether or not this buffer is backed by an accessible array. |
hasRemaining() | This method tells whether there are any elements between the current position and the limit. |
isDirect() | This method tells whether or not this buffer is direct. |
isReadOnly() | This method tells whether or not this buffer is read-only. |
limit() | This method returns this buffer's limit. |
limit(int newLimit) | This method sets this buffer's limit. |
mark() | This method sets this buffer's mark at its position. |
position() | This method returns this buffer's position. |
position(int newPosition) | This method sets this buffer's position. |
remaining() | This method returns the number of elements between the current position and the limit. |
reset() | This method resets this buffer's position to the previously marked position. |
rewind() | This method rewinds this buffer. |
Implementation: Buffer class and its methods
Example 1
Java
// Java program to demonstrate Buffer Class
// Importing required libraries
import java.nio.*;
import java.util.*;
// Main class
public 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);
}
}
}
Output The array is : [ 10 20 30 40 50 ]
Example 2
Java
// Java program to demonstrate Buffer class
// Importing required libraries
import java.nio.*;
import java.util.*;
// Main class
public 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);
}
}
}
Outputposition before reset: 5
position after reset: 0
Similar Reads
Java.io.BufferedWriter class methods in Java Bufferreader class writes text to character-output stream, buffering characters.Thus, providing efficient writing of single array, character and strings. A buffer size needs to be specified, if not it takes Default value. An output is immediately set to the underlying character or byte stream by the
5 min read
java.nio.FloatBuffer Class in Java A Buffer object can be termed as a container for a fixed amount of data. The buffer acts as a storing box, or temporary staging area, where data can be stored and later retrieved according to the usage. Java Buffer classes are the foundation or base upon which java.nio is built. Float buffers are cr
4 min read
java.net.Socket Class in Java The java.net.Socket class allows us to create socket objects that help us in implementing all fundamental socket operations. We can perform various networking operations such as sending, reading data and closing connections. Each Socket object that has been created using with java.net.Socket class h
5 min read
java.nio.LongBuffer Class in Java LongBuffer holds a sequence of long values to be used in an I/O operation. The LongBuffer class provides the following four categories of operations upon long buffers: Absolute and relative get and put methods that read and write single longs.Relative bulk get methods that transfer contiguous sequen
5 min read
Java.io.BufferedInputStream class in Java A BufferedInputStream adds functionality to another input stream-namely, the ability to buffer the input and to support the mark and reset methods. When the BufferedInputStream is created, an internal buffer array is created. As bytes from the stream are read or skipped, the internal buffer is refil
4 min read
java.nio.channels.Selector Class in Java A selector is a tool that helps you keep an eye on one or more NIO channels and figure out when they're ready to transfer data. In Java NIO, the Selector is a key player that looks at multiple Java NIO Channel instances and figures out which ones are good to go for actions like reading or writing. T
9 min read
java.nio.file.FileSystem class in java java.nio.file.FileSystem class provides an interface to a file system. The file system acts as a factory for creating different objects like Path, PathMatcher, UserPrincipalLookupService, and WatchService. This object help to access the files and other objects in the file system. Syntax: Class decla
4 min read
java.nio.charset.CoderResult Class in Java The 'java.nio.charset' package in Java contains classes for character encoding and decoding. The CoderResult class is used for determining the outcome of an encoding or decoding operation. Before we get started, let's review the ideas behind character encoding and decoding in CoderResult. The proces
6 min read
java.nio.file.FileStore Class in Java Java.nio.file is a package in java that consists of the FileStore class. FileStore class is a class that provides methods for the purpose of performing some operations on file store. FileStore is a class that extends Object from java.lang package. And few methods the FileStore class can inherit from
4 min read
Java.io.StringWriter class in Java Java StringWriter class creates a string from the characters of the String Buffer stream. Methods of the StringWriter class in Java can also be called after closing the Stream as this will raise no IO Exception. Declaration in Java StringWriter Classpublic class StringWriter extends WriterConstructo
6 min read