Updated June 19, 2023
Definition of Java nio ByteBuffer
Java nio bytebuffer is defined as direct or non-direct. Bytebuffer holds the integer value sequence used in an IO operation. The bytebuffer provides four categories of operation. The relative and absolute methods in Java nio bytebuffer read the single bytes. The relative and absolute methods in Java nio bytebuffer write the single bytes. We use to get and put methods in nio bytebuffer.
Introduction to Java nio ByteBuffer
The relative bulk gets and put method transforms the continuous sequences of bytes from the array, or it will contain another buffer in the array. In Java, nio bytebuffer is created to use two methods, i.e., allocate and wrap. The allocation method is used to allocate the space from the content of the specified buffer. The wrap method contains a long array of the specified buffer. To invoke the factory method, we create the direct buffer.
The buffer is returned to use the allocateDirect method; it will contain high deallocation and allocation cost. The direct buffer content will reside outside in the heap that was collected from garbage. We have recommended that direct buffers will be allocated primarily for large and native IO operations. The best direct buffers are measurable to gain the performance of the program.
Key Takeaways
- The bytebuffer class is the foundation on which the java nio bytebuffer class is built. In the java nio bytebuffer class is the most important and preferred.
- We use bytes to compose types of non-boolean primitives. We use bytes to transfer data between external IO devices and JVM.
Create Java nio ByteBuffer
Java provides the class of bytebuffer that contains the abstraction of a buffer that stores the values of the bytes. The bytebuffer can operate onto the FileChannel, which contains the byte channel for the current position. The file channel provides methods to read and write from byteBuffer.
The below steps show how we can create a nio bytebuffer as follows:
It will contain multiple steps as follows.
1. In the first step, we create the class name as java_bytebuffer and import the nio packages and util as follows.
Code:
import java.nio.*;
import java.util.*;
public class java_bytebuffer {
public static void main(String[] args) {
}
}
2. After the creation of the class and import of the packages, now in this step, we create and initialize the bytebuffer as follows. The bytebuffer is backed to use an array and provide facility as position.
Code:
ByteBuffer b = ByteBuffer.allocate(1024);
byte[] br = new byte[2048];
ByteBuffer buf = ByteBuffer.wrap(br);
3. After the creation and initialize the buffer, now in this step, we read and write in bytebuffer as follows.
Code:
String ifile = null;
FileInputStream in = new FileInputStream(ifile);
int len = in.getChannel().read(buf);
String ofile = null;
FileOutputStream out = new FileOutputStream(ofile);
out.getChannel().write(buf);
4. After the read and write data from the bytebuffer, now in this step, we can copy files from the bytebuffer as follows. Reads from the channel of InputStream return the -1. It sets the buffer of the pointer position to 0 and limits it to the read of the last byte. The byte is transferred from the pointer’s position; the buffer is cleared to reset the limit and position.
Code:
while ( in.getChannel().read(buf) != -1 ) {
buf.flip();
out.getChannel().write(buf);
buf.clear();
}
5. We can also convert the integer value into an array. Java nio bytebuffer is useful for byte conversion. The below example shows the nio bytebuffer as follows. For the conversion of an integer into a byte array, we use bytebuffer. We can also convert the other primitive types to byte arrays. In Java, bytebuffer does not provide a direct method to read and write data from bytebuffer.
Code:
import java.nio.*;
import java.util.*;
public class java_bytebuffer
{
public static void main(String[] args)
{
ByteBuffer buf = ByteBuffer.allocate(10);
int val = 3457;
buf.putInt(val);
buf.flip();
byte[] arr = buf.array();
System.out.print(" { ");
for(int i = 0; i < buf.limit(); i++)
System.out.println("0x%X, ", arr[i]);
System.out.println("}");
}
}
Output:
6. The big integer contains arbitrary precision in java. The below example shows the nio bytebuffer as follows. The math operation includes the class of big integers. We are using the bytebuffer store and converts big integer values.
Code:
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.*;
import java.util.*;
public class java_bytebuffer
{
public static void main(String[] args) throws IOException
{
BigInteger bint = new BigInteger("2378438748372478");
byte[] arr = bint.toByteArray();
System.out.println("%1$s" => { ", bint.toString());
for(int i = 0; i < arr.lenght; i++)
System.out.println("0x%X, ", arr[i]);
System.out.println("}");
buf.put(arr);
buf.flip();
out.getChannel().write(buf);
out.close ();
}
}
We use the below methods with java nio bytebuffer. We can use the limit, capacity, and position methods.
1. Limit
The limit method in a class of ByteBuffer actively sets the buffer’s limit. If the position exceeds that limit, it actively sets it as a new limit. The below syntax shows the limit in java nio bytebuffer as follows.
Syntax:
bytebuffer limit (int newlimit)
The below example shows the limit in java nio bytebuffer as follows.
Code:
import java.nio.*;
import java.util.*;
public class java_bytebuffer {
public static void main(String[] args)
{
ByteBuffer bf = ByteBuffer.allocate(4);
bf.put((byte)25);
bf.put((byte)35);
System.out.println("Before: "
+ Arrays.toString(bf.array())
+ "\nPosition: " + bf.position()
+ "\nLimit: " + bf.limit());
bf.limit(1);
System.out.println("\nAfter: "
+ Arrays.toString(bf.array())
+ "\nPos: " + bf.position()
+ "\nLimit: " + bf.limit());
}
}
2. Capacity
We can compute the capacity of java nio bytebuffer. The method of capacity can return the buffer capacity. The below example shows the java nio bytebuffer capacity method as follows.
Code:
import java.nio.*;
import java.util.*;
public class java_bytebuffer {
public static void main(String[] args)
{
int capacity = 15;
ByteBuffer bbf = ByteBuffer.allocate (capacity);
bbf.put ((byte)35);
bbf.put (4, (byte)55);
System.out.println (Arrays.toString (bbf.array()));
}
}
3. Position
The limit method in a class of bytebuffer is used to set the buffer’s position. The below syntax shows the limit in java nio bytebuffer as follows.
Syntax:
bytebuffer position (int newPosition)
The below example shows the position in java nio bytebuffer as follows.
Code:
import java.nio.*;
import java.util.*;
public class java_bytebuffer {
public static void main(String[] args)
{
ByteBuffer bbf = ByteBuffer.allocate (10);
bbf.position (1);
bbf.put ((byte)15);
bbf.position (7);
bbf.put ((byte)35);
System.out.println ("ByteBuffer: "
+ Arrays.toString (bbf.array()));
}
}
Java nio ByteBuffer Class Methods
Below are the methods of the java nio bytebuffer class as follows. Java nio bytebuffer contains multiple methods.
- allocate() – This method allocates the new bytebuffer.
- array() – This method returns the byte array.
- allocateDirect() – This method allocates a new byte buffer.
- arrayOffset() – This method returns an array from the buffer.
- asCharBuffer() – This method creates a view from the byte buffer as a char buffer.
- asDoubleBuffer() – This method creates the view of a double buffer as a double buffer.
- asFloatBuffer() – This method views the byte buffer as a float buffer.
- asIntBuffer() – This method creates the view of this byte buffer as an int buffer.
- asLongBuffer() – This method creates the view of this byte buffer as a long buffer.
- asReadOnlyBuffer() – This method creates a new read-only byte buffer that shares the buffer’s content.
- asShortBuffer() – This method views this byte buffer as a short buffer.
- compact() – This method compacts the buffer.
- compareTo() – This method compares one buffer with another.
- duplicate() – This method creates a new byte buffer from buffer content.
- equals() – This method tells buffer equal to another object.
- get() – This is relative to the get method and returns the buffer’s current position.
- getChar() – This method reads the char value and the char value from the current position.
- getDouble () – This method reads the double and double values from the current position.
- getFloat() – This method reads the float value and the float value from the current position.
- getInt () – This method reads the int value and reads the int value from the current position.
- getLong () – This method reads the long and long values from the current positions.
- getShort () – This method reads the short value and reads the short value from the current position.
- hasArray () – This method tells us a byte array backs the buffer.
- hashCode() – This method returns the current hash code.
- indirect() – This method tells whether the byte buffer is direct or not.
- order() – This method retrieves byte buffer order.
- put() – This method defines the put method.
- putChar() – This method defines the writing char value.
- putDouble() – This method defines the double writing value.
- putFloat() – This method defines the writing float value.
- putInt() – This method defines the writing char value.
- putLong() – This method defines the long writing value.
- putShort() – This method defines the writing short value.
- slice() – This method creates a buffer whose content is sharing buffers content.
- wrap() – This method wraps the byte array.
- toString() – This method returns the state of the buffer.
Java nio Alternative
The java.nio class represents nio. It allows us to do the non-blocking IO using channel and buffer. The channel is the same as a regular stream; we use a single channel to read and write from buffers. The buffer is nothing but the memory block where data is written, and we can read the same later.
The buffer contains the below essential properties as follows:
- Limit
- Capacity
- Position
The java nio IntBuffer class extends the superclass. The below example shows how we can create the IntBuffer class as follows.
Code:
import java.nio.*;
import java.util.*;
class java_bytebuffer {
public static void main(String[] args) {
int cap = 10;
int [] ia = {3, 1, 7};
IntBuffer b1 = IntBuffer.allocate (cap);
IntBuffer b2 = IntBuffer.wrap (ia);
b1.put (1, 31);
System.out.println (Arrays.toString (b1.array()));
System.out.println (Arrays.toString (b2.array()));
}
}
Conclusion
The buffer is returned to use the allocateDirect method; it will contain high deallocation and allocation cost. Bytebuffer holds the integer value sequence that was used in an IO operation. The bytebuffer in nio java provides four categories of operation. The relative and absolute methods in java nio bytebuffer read the single bytes.
Recommended Articles
We hope that this EDUCBA information on “Java nio ByteBuffer” was beneficial to you. You can view EDUCBA’s recommended articles for more information.