此文介绍nio中ByteBuffer的特性之一,视图.
*view buffer概念
---把ByteBuffer转换为其他数据类型的buffer,比如char,long,float等,这样就方便处理连续的多字节情况
---相关的api,形如as*Buffer,如LongBuffer asLongBuffer()之类
*功能特性(ByteBuffer注释中"views"条目有详细的注解)
---视图和原ByteBuffer共享数据,但各自独立位置信息.
"Changes to the byte buffer's content
will be visible in the view buffer, and vice versa; the two buffers'
position, limit, and mark values are independent."
---view buffer的字节次序在创建时被确定
"The byte order of a view buffer is fixed to be that of its byte buffer
at the time that the view is created. "
---优点
方便处理大块数据
*api分析
以子类HeapByteBuffer中的实现方式为例,其他类型的实现方式相同
CharBuffer java.nio.HeapByteBuffer.asCharBuffer()public CharBuffer asCharBuffer() {int size = this.remaining() >> 1; //char比byte多一个字节,容量/2int off = offset + position(); //offset从原buffer的position开始return (bigEndian? (CharBuffer)(new ByteBufferAsCharBufferB(this, //与原buffer共享数据-1, //mark =-10, //position =0size, //limit =sizesize, //compacity =sizeoff)) //offset =off: (CharBuffer)(new ByteBufferAsCharBufferL(this,-1,0,size,size,off))); } /* *1.view buffer的数据内容是原buffer的remaining部分 *2.view buffer和原buffer保持相同的字节顺序 */
*测试示例
示例ViewBufferTest/*** Feb 16, 2011 by dzh*/ package buffer.view;import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.CharBuffer;/*** @author dzh**/ public class ViewBufferTest {public static void main(String[] args) {ByteBuffer byteBuf =ByteBuffer.allocate(6).order(ByteOrder.BIG_ENDIAN);byteBuf.put((byte) 0).put((byte) 'A').mark();byteBuf.put(new byte[]{0,'B',0,'C'}).reset();CharBuffer charBuf =byteBuf.asCharBuffer();System.out.println(byteBuf.toString()); //java.nio.HeapByteBuffer[pos=2 lim=6 cap=6]System.out.println(charBuf.toString()); //BC}}