Java 中的 ByteBuffer allocate() 方法
可以使用類 `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]
廣告