Share on Google+Share on Google+

How to Create a ByteBuffer using Byte Array in java.

Advertisement
In this tutorial you will see how to Create a ByteBuffer using Byte Array in java.

How to create a ByteBuffer using Byte Array in java.

                In this tutorial, we will discuss how to creates a buffer using byte array. The ByteBuffer 
class is a container for handling data.The ByteBuffer class is available in java.nio package. 

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

Return type Method Description
static ByteBuffer wrap(byte array)  The wrap method create a byte buffer by wrapping  the associated byte arrray. 
final int capacity() The capacity() method returns the capacity of associated buffer.

code

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

public class ByteArrayBuffer {
  public static void main(String[] argsthrows Exception {
    byte[] size = new byte[255];
    FileInputStream finStream = new FileInputStream(args[0]);
    System.out.println("Name of file : " + args[0]);
    FileChannel fchannel = finStream.getChannel();
    ByteBuffer bytebuf = ByteBuffer.wrap(size);
    fchannel.read(bytebuf);
    System.out.println("Capacity of ByteArraytBuffer : "
        + bytebuf.capacity());
  }
}

Following is the output if you run the application:

C:\>java ByteArrayBuffer C:\Work\Bharat\load\ByteArrayBuffedr\bharat.txt
Name of file :C:\Work\Bharat\load\ByteArrayBuffedr\bharat.txt
Capacity of ByteArraytBuffer : 255

Download this code

Advertisements

Advertisement

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.