Java中的ByteBufferallocateDirect()方法
可以使用allocateDirect()java.nio.ByteBuffer类中的方法分配直接字节缓冲区。此方法需要一个参数,即以字节为单位的容量,它返回直接字节缓冲区。如果提供的容量为负,则抛出IllegalArgumentException。
演示此的程序如下所示-
示例
import java.nio.*;
import java.util.*;
public class Demo {
public static void main(String[] args) {
int n = 5;
try {
ByteBuffer buffer = ByteBuffer.allocateDirect(n);
byte[] byteValues = { 7, 1, 6, 3, 8 };
buffer = ByteBuffer.wrap(byteValues);
System.out.println("The direct ByteBuffer is: " + Arrays.toString(buffer.array()));
System.out.println("\nThe state of the ByteBuffer is: ");
System.out.println(buffer.toString());
} catch (IllegalArgumentException e) {
System.out.println("Error!!! IllegalArgumentException");
} catch (ReadOnlyBufferException e) {
System.out.println("Error!!! ReadOnlyBufferException");
}
}
}输出结果
The direct ByteBuffer is: [7, 1, 6, 3, 8] The state of the ByteBuffer is: java.nio.HeapByteBuffer[pos=0 lim=5 cap=5]
热门推荐
1 带狗狗训练
4 听力训练狗狗
6 怎训练狗狗
7 腹肌训练狗狗
8 网球训练狗狗
9 记叙文训练狗狗
10 狗狗太凶怎么训练
11 核心力量训练狗狗
12 狗狗乱叫怎么训练
13 发音训练狗狗
14 怎么训练狗狗叼东西给主人
15 荆州训练狗狗
16 篮球训练狗狗
17 做训练狗狗
18 训练狗狗坐姿