How to compute limit of ByteBuffer in java.


 

How to compute limit of ByteBuffer in java.

In this tutorial you will see 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.

code

import java.io.*;
import java.nio.*;
import java.io.FileInputStream;
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 = fchannel.read(byteBuf);
    System.out.println("Limit of buffer at writing mode : "
        (byteBuf.limit()));
    byteBuf.flip();
    while (byteBuf.hasRemaining()) {
      System.out.print((charbyteBuf.get());
    }
    System.out.println("\n");
    System.out.println("Limit of buffer at reading mode : "
        (byteBuf.limit()));
  }
}

Following is the output if you run the application:

C:\>java ByteBufferLimit
Limit of buffer at writing mode : 48
import java.io.*;
Limit of buffer at reading mode : 17

Download this code

Ads