可以使用java.nio.ByteBuffer类中的方法allocate()分配新的ByteBuffer。该方法需要一个参数,即缓冲区的容量。它返回分配的新的ByteBuffer。如果提供的容量为负,则抛出IllegalArgumentException。
演示此的程序如下所示-
import java.nio.*;
import java.util.*;
public class Demo {
public static void main(String[] args) {
int n = 5;
try {
ByteBuffer buffer = ByteBuffer.allocate(n);
buffer.put((byte)1);
buffer.put((byte)2);
buffer.put((byte)3);
buffer.put((byte)4);
buffer.put((byte)5);
buffer.rewind();
System.out.println("The ByteBuffer is: " + Arrays.toString(buffer.array()));
} catch (IllegalArgumentException e) {
System.out.println("Error!!! IllegalArgumentException");
} catch (ReadOnlyBufferException e) {
System.out.println("Error!!! ReadOnlyBufferException");
}
}
}输出结果
The ByteBuffer is: [1, 2, 3, 4, 5]