我们通过一个实例BufferCharView来说明视图缓冲区和原始缓冲区的关系;
我们创建一个原始的字节缓冲区,存入“Hi!”;
在创建这个字节缓冲区的一个字符缓冲区视图,打印连个缓冲区的position、limit、capacity和内容进行观察:
package com.z;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.CharBuffer;
public class BufferCharView {
public static void main(String[] args){
ByteBuffer byteBuffer = ByteBuffer.allocate(7);
CharBuffer charBuffer = byteBuffer.asCharBuffer();
byteBuffer.order(ByteOrder.BIG_ENDIAN);
byteBuffer.put(0,(byte)0);
byteBuffer.put(1,(byte)'h');
byteBuffer.put(2,(byte)0);
byteBuffer.put(3,(byte)'i');
byteBuffer.put(4,(byte)0);
byteBuffer.put(5,(byte)'!');
byteBuffer.put(6,(byte)0);
print(byteBuffer);
print(charBuffer);
}
private static void print(Buffer buffer){
System.out.println("pos=" + buffer.position()
+ ", limit=" + buffer.limit()
+ ", capacity=" + buffer.capacity()
+ ": '" + buffer.toString() + "'");
}
}
pos=0, limit=7, capacity=7: 'java.nio.HeapByteBuffer[pos=0 lim=7 cap=7]'
pos=0, limit=3, capacity=3: 'hi!'
我们可以观察代码和结果来进行理解。
在这里我们留一个问题,问什么例子中的字节缓冲区要使用大端字节顺序???