public static void main(String[] args) throws IOException {
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
byteBuffer.putInt(1);
byteBuffer.putChar('a');
byteBuffer.flip();
int anInt = byteBuffer.getInt();
char aChar = byteBuffer.getChar();
//读取顺序必须一致否则报错
System.out.println(anInt);
System.out.println(aChar);
}
ByteBuffer 接口有4个类实现,后缀R表示只读。不可执行put方法,一旦执行,直接抛出异常,源码其实就是就是new一个异常。
DirectByteBuffer,DirectByteBufferR,HeapByteBuffer,HeapByteBufferR
默认的allcate方法就是返回的HeapByteBuffer
public static ByteBuffer allocate(int capacity) {
if (capacity < 0)
throw new IllegalArgumentException();
return new HeapByteBuffer(capacity, capacity);
}