Java ByteBuffer allocateDirect()方法及示例
java.nio.ByteBuffer 类的 allocateDirect() 方法是用来分配一个新的直接字节缓冲区。
新的缓冲区的位置将是零,它的极限是它的容量,它的标记将是未定义的,它的每个元素将被初始化为零。它是否有一个支持数组是未指定的。
这个方法比allocate()方法快25%-75%。
语法
public static ByteBuffer allocateDirect(int capacity)
参数: 该方法以字节为单位接收容量,作为参数。
返回值: 该方法返回新的字节缓冲区。
异常: 如果容量是一个负整数,该方法会抛出 IllegalArgumentException 。
下面是一些例子来说明allocateDirect()方法。
例子 1 :
// Java program to demonstrate
// allocateDirect() method
import java.nio.*;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// Declaring the capacity of the ByteBuffer
int capacity = 4;
// Creating the ByteBuffer
try {
// creating object of ByteBuffer
// and allocating size capacity
ByteBuffer bb = ByteBuffer.allocateDirect(capacity);
// creating byte array of size capacity
byte[] value = { 20, 30, 40, 50 };
// wrap the byte array into ByteBuffer
bb = ByteBuffer.wrap(value);
// print the ByteBuffer
System.out.println("Direct ByteBuffer: "
+ Arrays.toString(bb.array()));
// print the state of the buffer
System.out.print("\nState of the ByteBuffer : ");
System.out.println(bb.toString());
}
catch (IllegalArgumentException e) {
System.out.println("Exception thrown : " + e);
}
catch (ReadOnlyBufferException e) {
System.out.println("Exception thrown : " + e);
}
}
}
输出。
Direct ByteBuffer: [20, 30, 40, 50]
State of the ByteBuffer : java.nio.HeapByteBuffer[pos=0 lim=4 cap=4]
示例2: 显示IllegalArgumentException
// Java program to demonstrate
// allocateDirect() method
import java.nio.*;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// Declaring the capacity
// with negative value
int capacity = -4;
// Creating the ByteBuffer
try {
// creating object of ByteBuffer
// and allocating size capacity
System.out.println("Trying to allocate"
+ " negative value in ByteBuffer");
ByteBuffer bb = ByteBuffer.allocateDirect(capacity);
// creating byte array of size capacity
byte[] value = { 20, 30, 40, 50 };
// wrap the byte array into ByteBuffer
bb = ByteBuffer.wrap(value);
// print the ByteBuffer
System.out.println("Direct ByteBuffer: "
+ Arrays.toString(bb.array()));
// print the state of the buffer
System.out.print("\nState of the ByteBuffer : ");
System.out.println(bb.toString());
}
catch (IllegalArgumentException e) {
System.out.println("Exception thrown : " + e);
}
catch (ReadOnlyBufferException e) {
System.out.println("Exception thrown : " + e);
}
}
}
输出。
Trying to allocate negative value in ByteBuffer
Exception thrown : java.lang.IllegalArgumentException: Negative capacity: -4
极客教程