Thursday, May 2, 2024
HomeJavaByteBuffer Learn Write Instance in Java

ByteBuffer Learn Write Instance in Java


Howdy guys, in case you have labored with Java NIO API then there’s a good likelihood that you could be be conversant in ByteBuffer, one of many vital class which is used to learn and write knowledge from channels. Java NIO Buffers are used when interacting with NIO Channels like FileChannel. As you recognize, knowledge is learn from channels into buffers, and written from buffers into channels. A buffer is actually a block of reminiscence into which you’ll write knowledge, which you’ll then later learn once more. This reminiscence block is wrapped in an NIO Buffer object, which gives a set of strategies that makes it simpler to work with the reminiscence block. In the event you examine this with conventional java.io bundle then you’ll do not forget that we learn and write knowledge from stream into array however in case of NIO, we learn and write knowledge from channels into ByteBuffer

In case you are questioning the right way to learn and write knowledge from Buffer then don’t be concerned on this article I’ll present you the way to try this. One of many key factor to recollect is that once you learn knowledge from a ByteBuffer, the place you will have written knowledge, you first must flip the buffer. That is an vital step which many Java Programmer overlook.

Additionally, there are two sorts of ByteBuffer direct and in-direct byte buffer, In case of direct byte buffer JVM will make greatest effort to carry out native IO operation straight upon the buffer whereas in case of in-direct buffer it would use JDK API. 

If you wish to be taught extra about direct and non-direct buffer, then I additionally recommend you to checkout my earlier put up about distinction between direct, mapped and non-direct buffer in Java. 

Java Program to learn and write knowledge from ByteBuffer

Right here is our full Java program to exhibit the right way to learn knowledge from buffer and the right way to write knowledge into ByteBuffer utilizing allocateDirect() and allocate() technique in Java.  While you use allocateDirect() technique then a DirectByteBuffer is created the place JVM can carry out native learn and write operation.  Each allocate() and allocateDirect() takes one parameter, the capability of the buffer. 

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
 
/**
*
* Java Program to learn and write from ByteBuffer.
* You'll be able to create direct buffer or on heap ByteBuffer 
* utilizing allocateDirect() and allocate() technique.
*
* @creator Javin
*/
public class ByteBufferDemo {
 
    public static void essential(String args[]) {
 
        // Creates and initialize ByteBuffer in Java
        ByteBuffer buffer = ByteBuffer.allocate(1024);
 
        System.out.printf("new buffer, place : %s, restrict : %s,
                                         and capability : %s %n",
        buffer.place(), buffer.restrict(), buffer.capability());
 
        System.out.println("writing integer, lengthy and double into byte buffer");
        buffer.putInt(20); // 4 bytes written
        buffer.putLong(400000032); // 8 bytes written
        buffer.putDouble(21.3); // 8 bytes written
 
        System.out.printf("After writing, place : %s, restrict : %s,
                                        and capability : %s %n",
                buffer.place(), buffer.restrict(), buffer.capability());
 
        // flip the buffer to learn knowledge
        buffer.flip();
 
        System.out.printf("After flip, place : %s, restrict : %s,
                                        and capability : %s %n",
                buffer.place(), buffer.restrict(), buffer.capability());
 
        System.out.println("Studying integer from ByteBuffer in Java : " 
                                + buffer.getInt());
        System.out.println("Studying lengthy from ByteBuffer in Java : " 
                                + buffer.getLong());
        System.out.println("Studying double from ByteBuffer in Java : " 
                                + buffer.getDouble());
 
        // you'll be able to clear buffer for reuse
        buffer.clear();
 
        System.out.printf("After clearing ByteBuffer, place : %s, 
                         restrict : %s, and capability : %s %n",
                buffer.place(), buffer.restrict(), buffer.capability());
 
    }
 
}
 
Output
new buffer, place : 0, restrict : 1024, and capability : 1024
writing integer, lengthy and double into byte buffer
After writing, place : 20, restrict : 1024, and capability : 1024
After flip, place : 0, restrict : 20, and capability : 1024
Studying integer from ByteBuffer in Java : 20
Studying lengthy from ByteBuffer in Java : 400000032
Studying double from ByteBuffer in Java : 21.3
After clearing ByteBuffer, place : 0, restrict : 1024, and capability : 1024

You’ll be able to see that once we first created ByteBuffer utilizing allocate() technique it settle for one single parameter which is capability of the buffer. After creating, you may also see  that place factors to 0 whereas each restrict and capability variable factors to 1024, the precise restrict of buffer we supplied once we created it.

While you begin writing knowledge into ByteBuffer, you’ll be able to see that place step by step begin shifting to empty location however each restrict and capability stays identical and nonetheless level to the utmost index the place knowledge could be written.

Once we finished with writing and flip the buffer to learn knowledge from it, you’ll be able to see that place variable reset to 0 and restrict factors to the final place worth in write mode however capability stays identical. 

Here’s a good diagram which properly explains the studying and writing knowledge into Buffer, you’ll be able to see that in write mode each restrict and capability factors to identical location however in case of learn mode, restrict really factors till knowledge is written.

ByteBuffer Read Write Example in Java

Necessary factors to find out about ByteBuffer in Java

1. There isn’t a put() technique to jot down boolean sort into ByteBuffer in Java. So you’ll be able to both use 0 or 1 to characterize boolean true and false or can use “Y” and “N”. You’ll be able to retailer these by utilizing putChar() or put() technique

2. ByteBuffers are Not protected to be used by a number of concurrent threads

3. After I/O operation is initiated then should take nice care to not entry buffer till I/O operation completes

4. Reminiscence necessities for buffers depend upon the variety of excellent I/O operations

5. Heap buffers incur extra copy per I/O As per SocketChannel API, examine the efficiency

6. Copy efficiency and non permanent direct buffer utilization improved


That is all about the right way to use ByteBuffer in Java. On this Java NIO tutorial, you will have realized the right way to learn, write and work with ByteBuffer in Java. This is likely one of the core class to work with Bytes and NIO lessons like FileChannels and ServerSockets. I extremely advocate each Java developer to study ByteBuffer, its a vital idea however its not that intuitive, particularly the right way to learn and write on Buffer as a result of it’s worthwhile to flip the buffer, which confuses many programmer and causes points. 

Different Java IO and NIO tutorials chances are you’ll like:

Thanks for studying this text thus far. In the event you like this ByteBuffer tutorial in Java then please share it with your pals and colleagues. In case you have any questions or suggestions then please drop a word.



RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments