Home Tutorial Java Corejava Nio How to write the given byte into byte buffer.

 
 

Share on Google+Share on Google+
How to write the given byte into byte buffer.
Posted on: July 27, 2010 at 12:00 AM
Advertisement
In this tutorial you will see how to write the given byte into byte buffer.

How to write the given byte into byte buffer.

 In this tutorial, we will see how to writes the byte into byte buffer by using 
put(byte b) method of ByteBuffer class.

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 put(byte b) The put(..) method write byte into associated buffer and increment position.
abstract byte get() The get() method read byte from current position and increment position.

code

import java.nio.*;
import java.nio.ByteBuffer;

public class PutByte {
  public static final int capacity = 9;
  public static void main(String[] args) {
    try {
      ByteBuffer byteBuf = ByteBuffer.allocate(capacity);
      for (int i = 0; i < 9; i++) {
        byteBuf.put((byte) ('1' + i));
      }
      byteBuf.rewind();
      System.out.print("\nContents of buffer :");
      while (byteBuf.hasRemaining()) {
        System.out.print((charbyteBuf.get());
      }
    catch (Exception e) {
      System.out.println(e);
    }
  }
}

Output

C:\>java PutByte
Contents of buffer :123456789

Download this code

Advertisement

Related Tags for How to write the given byte into byte buffer.:


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