nio~view buffer
此文介紹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}}轉載于:https://www.cnblogs.com/bronte/articles/1955914.html
總結
以上是生活随笔為你收集整理的nio~view buffer的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 中信i白金信用卡额度是多少?申请的条件是
- 下一篇: 指针08 - 零基础入门学习C语言48