Write a byte into byte buffer at given index.


 

Write a byte into byte buffer at given index.

In this tutorial you will see how to write a byte into byte buffer at given index.

In this tutorial you will see how to write a byte into byte buffer at given index.

Write a byte into byte buffer at given index.

 In this tutorial, we will see how to write the given byte into byte buffer at the given 
index.

ByteBuffer API:

The java.nio.ByteBuffer class extends java.nio.Buffer class. It provides the following methods:

Return type Method Description
static ByteBuffer allocate(int capacity)  The allocate(..)method allocate a new byte buffer.
abstract ByteBuffer putChar(int index, byte b) The putChar(..) method write two byte containing the given character value into associated buffer.
abstract byte get() The get() method read byte from current position and increment position.

code

import java.nio.*;
import java.nio.ByteBuffer;
public class PutAtIndex {
  public static final int capacity = 9;
  public static void main(String[] args) {
    try {
     ByteBuffer byteBuf = ByteBuffer.allocate(capacity);
      int i = 3;
      System.out.println("Write value at index : " + i);
      byteBuf.putChar(i, 'B');
      byteBuf.rewind();
System.out.print("\nRead value from index " + i + " : ");
      while (byteBuf.hasRemaining()) {
        System.out.print((charbyteBuf.get());
      }
    catch (Exception e) {
      System.out.println(e);
    }
  }
}

Output

C:\>java PutAtIndex
Write value at index  : 3
Read value from index 3 : B

Download this code

Ads