Home Tutorial Java Corejava Nio Use of isDirect() method of byte buffer class in java.

 
 

Use of isDirect() method of byte buffer class in java.
Posted on: July 28, 2010 at 12:00 AM
Advertisement
In this tutorial you will see the use of isDirect() method of ByteBuffer class in java.

Use of isDirect() method of ByteBuffer class in java.

In this tutorial, we will check buffer is direct or not.

ByteBuffer API.

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

Return type Method Description
abstract boolean isDirect() The isDirect() method tells whether this associated buffer is direct or not.
static ByteBuffer wrap(byte[] array)  The wrap(...) method create a byte buffer by wrapping  the associated byte array. 
static ByteBuffer allocate( int capacity)  The allocate() method allocate a byte buffer.
static ByteBuffer allocateDirect( int capacity)  The allocateDirect()method allocate a direct byte buffer.

code

import java.nio.*;
import java.nio.ByteBuffer;

public class BufferIsDirect {
  public static final int size = 256;

public static void main(String[] argvthrows Exception {
    byte[] bytes = new byte[size];
    ByteBuffer bbuf = ByteBuffer.wrap(bytes);
    boolean isDirect = bbuf.isDirect();
    if (isDirect) {
   System.out.println("ByteBuffer direct allocated");
    else {
   System.out.println("ByteBuffer not direct allocated");
    }
    bbuf = ByteBuffer.allocate(size);
    isDirect = bbuf.isDirect();
    if (isDirect) {
      System.out.println("ByteBuffer direct allocated");
    else {
   System.out.println("ByteBuffer not direct allocated");
    }
    bbuf = ByteBuffer.allocateDirect(size);
    isDirect = bbuf.isDirect();
    if (isDirect) {
      System.out.println("ByteBuffer direct allocated");
    else {
   System.out.println("ByteBuffer not direct allocated");
    }
  }
}

Following is the output if you run the application:

C:\>java BufferIsDirect
ByteBuffer not direct allocated
ByteBuffer not direct allocated
ByteBuffer direct allocateed

Download this code

Advertisement

Related Tags for Use of isDirect() method of byte buffer class 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 28, 2010

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com