Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Java nio ByteBuffer

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 get and put methods in nio bytebuffer.

Introduction to Java nio ByteBuffer

The relative bulk get 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. The direct buffer is created to invoke the factory method.

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 a 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 shows 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, also import the packages of nio 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 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 set the buffer of the pointer position to 0 and limits to the read of the last byte. The byte is transferred from the position of the pointer, then 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 nio bytebuffer as follows. For 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 

Output:

6. The big integer contains arbitrary precision in java. The below example shows 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 

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 is used to set the limit of the buffer. If the position is large than that limit then it will be set 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 position of the buffer. 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 creates a view of 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 content of the buffer.
  • asShortBuffer () – This method creates a view of this byte buffer as a short buffer.
  • compact () – This method compact 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 current position of the buffer.
  • getChar () – This method reads the char value and also reads the char value from the current position.
  • getDouble () – This method reads the double value and also reads the double value from the current position.
  • getFloat () – This method reads the float value and also reads 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 value and also reads the long value from the current position.
  • getShort () – This method reads the short value and reads the short value from the current position.
  • hasArray () – This method tells us the buffer is backed by a byte array.
  • hashCode () – This method returns the current hash code.
  • indirect () – This method tells whether the byte buffer is direct or not.
  • order () – This method retrieve byte buffer order.
  • put () – This method defines the put method.
  • putChar () – This method defines the writing char value.
  • putDouble () – This method defines the writing double value.
  • putFloat () – This method defines the writing float value.
  • putInt () – This method defines the writing char value.
  • putLong () – This method defines the writing long 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

This is a guide to Java nio ByteBuffer. Here we discuss the introduction, creation of java nio ByteBuffer, class methods, and alternative. You can also look at the following articles to learn more –

  1. Java Projects Resume
  2. Java Garbage Collectors Types
  3. Java Projects for Final Year
  4. Java HTTP Client

The post Java nio ByteBuffer appeared first on EDUCBA.



This post first appeared on Free Online CFA Calculator Training Course | EduCB, please read the originial post: here

Share the post

Java nio ByteBuffer

×

Subscribe to Free Online Cfa Calculator Training Course | Educb

Get updates delivered right to your inbox!

Thank you for your subscription

×