Share on Google+Share on Google+

How to get specific index value from ByteBuffer in java.

In this tutorial you will see how to get specific index value from ByteBuffer in java.

How to get specific index value from ByteBuffer in java.

             In this tutorial, we will discuss how to get value of a given index from buffer. The ByteBuffer 
class is a container for handling data. The get(int index) method of ByteBuffer class returns value 
of a given index. The method allocate( int capacity) creates a new byte buffer, and the current position 
will be zero and its limit will be it's capacity. 

About 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 create a byte buffer of specified capacity. 
byte get(int index) The get() method reads bytes at given index  from  buffer.


import java.nio.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class GetIndexValue {
  public static void main(String[] argsthrows IOException {
    int index = 4;
    FileInputStream aFile = new FileInputStream("testfile1.txt");
    FileInputStream bFile = new FileInputStream("testfile2.txt");
    FileChannel inChannel = aFile.getChannel();
    FileChannel inChannelb = bFile.getChannel();
    ByteBuffer buf = ByteBuffer.allocate(256);
    int bytesRead =;
System.out.println("Value in first buffer at index " + index + ": "
    int bytesReadb =;
System.out.println("Value in second buffer at index " + index + ": "


C:\Work\Bharat\load\getSpecified value>java GetIndexValue
Value in first buffer at index 4 : r
Value in second buffer at index 4 : a

Download this code



Posted on: July 26, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial 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.


Advertisement null