Share on Google+Share on Google+

How to compute limit of ByteBuffer in java.

In this tutorial you will see how to compute limit of ByteBuffer in java.

How to compute limit of ByteBuffer in java.

               In this tutorial, we will discuss about the limit of buffer. The ByteBuffer class 
is a container for handling primitive data type. The Limit() method is returns the limit of the
 buffer. The ByteBuffer class is available in java.nio package. 

         In this example, we will compute the limit of buffer in write and read mode. In the 
writing mode the limit of buffer will be capacity of buffer, and in read mode the limit of 
buffer is how much data you can read. The method allocate( int capacity) creates a new 
byte buffer. The FileChannel class creates a channel for reading, and writing file. 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. 
int limit() The limit() method returns the limit of buffer in read or wrirte mode.


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

public class ByteBufferLimit {
public static void main(String[] argsthrows IOException {
FileInputStream InStream = new FileInputStream("test.txt");
    FileChannel fchannel = InStream.getChannel();
    ByteBuffer byteBuf = ByteBuffer.allocate(48);
    int bytesRead =;
    System.out.println("Limit of buffer at writing mode : "
    while (byteBuf.hasRemaining()) {
    System.out.println("Limit of buffer at reading mode : "

Following is the output if you run the application:

C:\>java ByteBufferLimit
Limit of buffer at writing mode : 48
Limit of buffer at reading mode : 17

Download this code


Posted on: July 24, 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