Home Tutorial Java Corejava Nio How to Create a ByteBuffer using Byte Array in java.

 
 

How to Create a ByteBuffer using Byte Array in java.
Posted on: July 26, 2010 at 12:00 AM
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

Advertisement

Related Tags for How to Create a ByteBuffer using Byte Array 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