Home Tutorial Java Corejava Nio How to get the capacity of ByteBuffer in java.

 
 

How to get the capacity of ByteBuffer in java.
Posted on: July 24, 2010 at 12:00 AM
Advertisement
In this tutorial you will see how to get the capacity of ByteBuffer in java.

How to get the capacity  of ByteBuffer in java.

                In this tutorial, we will discuss how to get the capacity of buffer. The ByteBuffer 
class is a container for handling data. The ByteBuffer class is available in java.nio package. 

         In this example, we will compute the capacity of buffer. The capacity() method returns
the capacity of buffer. The method allocate( int capacity) creates a new byte buffer. The
FileChannel class creates a channel for reading, and writing file. The FileChannel is similar 
to the stream but they are few different. The channel can read write both, but stream can either 
read-only or write-only. The getChannel method of FileInputStream class returns the 
Channel associated with this file input stream. The read() method of FileChannel class 
fills byte buffer created by using allocate() method.

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. 
final int capacity() The capacity() method returns the capacity og associated buffer.

code

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

public class ByteBufferCapacity {
  public static final int size = 1024;
public static void main(String[] argsthrows Exception {
FileInputStream finStream = new FileInputStream(args[0]);
    System.out.println("Given file name :" + args[0]);
    FileChannel fchannel = finStream.getChannel();
    ByteBuffer bytebuf = ByteBuffer.allocate(size);
    fchannel.read(bytebuf);
System.out.println("Capacity of ByteBuffer : " 

+ bytebuf.capacity());
  }
}

Following is the output if you run the application:

C:\>java ByteBufferCapacity  C:\Work\Bharat\load\ByteBuffercapicity\test.txt
Given file name :C:\Work\Bharat\load\ByteBuffercapicity\test.txt
Capacity of ByteBuffer : 1024

Download this code

Advertisement

Related Tags for How to get the capacity of 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 24, 2010

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com