ByteBuffer 的 `allocateDirect()` 方法在 Java 中
可以使用 java.nio.ByteBuffer 類中的方法 `allocateDirect()` 分配一個直接位元組緩衝區。此方法需要一個引數,即以位元組為單位的容量,它返回直接位元組緩衝區。如果提供的容量為負數,則會引發 `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("
The 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]
廣告