Home Tutorial Java Corejava Nio How to get specific index value from ByteBuffer in java.

 
 

Share on Google+Share on Google+
How to get specific index value from ByteBuffer in java.
Posted on: July 26, 2010 at 12:00 AM
Advertisement
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.

code

import java.io.*;
import java.nio.*;
import java.io.FileInputStream;
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 = inChannel.read(buf);
    buf.flip();
System.out.println("Value in first buffer at index " + index + ": "
        (charbuf.get(index));
    buf.clear();
    int bytesReadb = inChannelb.read(buf);
    buf.flip();
System.out.println("Value in second buffer at index " + index + ": "
        (charbuf.get(index));
   }
}

output

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

Advertisement

Related Tags for How to get specific index value from ByteBuffer in java.:


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 26, 2010

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com