Home Tutorial Java Corejava Nio Write a byte into byte buffer at given index.

 
 

Share on Google+Share on Google+
Write a byte into byte buffer at given index.
Posted on: July 27, 2010 at 12:00 AM
Advertisement
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

Advertisement

Related Tags for Write a byte into byte buffer at given index.:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: July 27, 2010

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com