ByteBuffer的使用
轉載自? ??ByteBuffer的使用
ByteBuffer
字節緩存區處理子節的,比傳統的數組的效率要高。
分類
HeapByteBuffer
用子節數組封裝的一種的ByteBuffer,分配在堆上,受GC控制。
DircectByteBuffer
不是分配在堆上,不受GC控制?
兩者的區別?
1,創建和釋放DirectByteBuffer的代價要比HeapByteBuffer要高,?
2,DirectByteBuffer的讀寫的操作要比HeapByteBuffer要快
使用
創建
1.獲取HeadByteBuffer
ByteBuffer heapByteBuffer = ByteBuffer.allocate(20);其中ByteBuffer.allocate(20);
public static ByteBuffer allocate(int capacity) {if (capacity < 0)throw new IllegalArgumentException();return new HeapByteBuffer(capacity, capacity); }HeapByteBuffer(int cap, int lim, boolean isReadOnly) { // package-privatesuper(-1, 0, lim, cap, new byte[cap], 0);this.isReadOnly = isReadOnly; }ByteBuffer(int mark, int pos, int lim, int cap, byte[] hb, int offset) {super(mark, pos, lim, cap, 0);this.hb = hb;this.offset = offset; }新生成了一個長度為capacity的數組,以及一些標示
2.獲取DirectByteBuffer對象
ByteBuffer directByteBuffer = ByteBuffer.allocateDirect(20);其中ByteBuffer.allocateDirect(20);
public static ByteBuffer allocateDirect(int capacity) {if (capacity < 0) {throw new IllegalArgumentException("capacity < 0: " + capacity);}DirectByteBuffer.MemoryRef memoryRef = new DirectByteBuffer.MemoryRef(capacity);return new DirectByteBuffer(capacity, memoryRef); }MemoryRef(int capacity) {VMRuntime runtime = VMRuntime.getRuntime();buffer = (byte[]) runtime.newNonMovableArray(byte.class, capacity + 7);allocatedAddress = runtime.addressOf(buffer);// Offset is set to handle the alignment: http://b/16449607offset = (int) (((allocatedAddress + 7) & ~(long) 7) - allocatedAddress);isAccessible = true; }由runtime去申請了了一塊內存。不是直接在堆內存中。
基本操作
再說基本操作之前,先簡單說下的ByteBuffer常見的四個標示?
1. position:當前讀或者寫的位置?
2. mark:標記上一次mark的位置,方便reset將postion置為mark的值。?
3. limit:標記數據的最大有效的位置?
4. capacity:標記buffer的最大可存儲值?
其中在任意的時候。都必須滿足?
mark<=position<=limit<=capacity?
這里以HeapByteBuffer為例?
1.put()?
position+1,mark不變,limit 不變,capacity不變
打印的結果
capacity: 20 ,limit: 20 ,position: 0 ,mark: -1 capacity: 20 ,limit: 20 ,position: 10 ,mark: -1源碼
//put public ByteBuffer put(byte x) {if (isReadOnly) {throw new ReadOnlyBufferException();}hb[ix(nextPutIndex())] = x;return this; }//nextPutIndex final int nextPutIndex(){if(position>=limit){throw new BufferOverflowException();}return position++; }2.get()?
position++,mark不變,limit不變,capacity不變
打印結果
capacity: 20 ,limit: 20 ,position: 0 ,mark: -1 0000000000 capacity: 20 ,limit: 20 ,position: 10 ,mark: -1解釋下,初始化,該數組的默認值為0,每次調用get的方法,position+1?
源碼
3.filp()?
limit=position,position=0,capacity不變,mark=-1?
模擬一次讀寫
打印的結果
after create capacity: 20 ,limit: 20 ,position: 0 ,mark: -1 after put capacity: 20 ,limit: 20 ,position: 10 ,mark: -1 after flip capacity: 20 ,limit: 10 ,position: 0 ,mark: -1 0123456789 after get capacity: 20 ,limit: 10 ,position: 10 ,mark: -1源碼
public final Buffer flip() {limit = position;position = 0;mark = -1;return this; }4.rewind?
position=0,mark =-1,limit 不變,capacity不變
打印
after create capacity: 20 ,limit: 20 ,position: 0 ,mark: -1 after put capacity: 20 ,limit: 20 ,position: 10 ,mark: -1 after rewind capacity: 20 ,limit: 20 ,position: 0 ,mark: -1 0123456789 after get capacity: 20 ,limit: 20 ,position: 10 ,mark: -1乍一看似乎和flip的沒什么區別。但是我們最大ByteBuffer有效數據是到limit的截止的,這也意味著如果在讀寫切換操作的時候,你使用rewind的時候,會將一部分臟數據讀出來。例如下面的�例子
ByteBuffer heapByteBuffer = ByteBuffer.allocate(20); printField("after create", heapByteBuffer); //寫操作 for (int i = 0; i < 10; i++) {heapByteBuffer.put((byte) i); } printField("after put", heapByteBuffer);heapByteBuffer.rewind(); printField("after rewind", heapByteBuffer); //讀操作 for (int i = 0; i < heapByteBuffer.limit(); i++) {System.out.print(heapByteBuffer.get()); } System.out.println(); printField("after get", heapByteBuffer);打印的結果
after create capacity: 20 ,limit: 20 ,position: 0 ,mark: -1 after put capacity: 20 ,limit: 20 ,position: 10 ,mark: -1 after rewind capacity: 20 ,limit: 20 ,position: 0 ,mark: -1 01234567890000000000 after get capacity: 20 ,limit: 20 ,position: 20 ,mark: -1我們會面發現后面10個0并不是我們實現寫進去的,但是讀的時候卻讀出來了,如果我們使用flip的操作的時候
ByteBuffer heapByteBuffer = ByteBuffer.allocate(20); printField("after create", heapByteBuffer); //寫數據 for (int i = 0; i < 10; i++) {heapByteBuffer.put((byte) i); } printField("after put", heapByteBuffer);heapByteBuffer.flip(); printField("after flip", heapByteBuffer); //讀數據 for (int i = 0; i < heapByteBuffer.limit(); i++) {System.out.print(heapByteBuffer.get()); } System.out.println(); printField("after get", heapByteBuffer);打印的結果為
after create capacity: 20 ,limit: 20 ,position: 0 ,mark: -1 after put capacity: 20 ,limit: 20 ,position: 10 ,mark: -1 after flip capacity: 20 ,limit: 10 ,position: 0 ,mark: -1 0123456789 after get capacity: 20 ,limit: 10 ,position: 10 ,mark: -1源碼
public final Buffer rewind() {position = 0;mark = -1;return this; }5.clear()?
position=0,mark =-1,capacity不變,limit=capacity
打印的結果
after create capacity: 20 ,limit: 20 ,position: 0 ,mark: -1 after put capacity: 20 ,limit: 20 ,position: 10 ,mark: -1 after flip capacity: 20 ,limit: 10 ,position: 0 ,mark: -1 0123456789 after get capacity: 20 ,limit: 10 ,position: 10 ,mark: -1 after clear capacity: 20 ,limit: 20 ,position: 0 ,mark: -1 01234567890000000000 after get capacity: 20 ,limit: 20 ,position: 20 ,mark: -1可以看到并沒有影響buffer的數據?
源碼
6.mark()?
7.reset()?
mark():mark = position?
reset():position = mark;
打印的結果
after create capacity: 20 ,limit: 20 ,position: 0 ,mark: -1 after put capacity: 20 ,limit: 20 ,position: 10 ,mark: -1 after mark capacity: 20 ,limit: 20 ,position: 10 ,mark: 10 after position capacity: 20 ,limit: 20 ,position: 15 ,mark: 10 after reset capacity: 20 ,limit: 20 ,position: 10 ,mark: 10源碼
//mark public final Buffer mark() {mark = position;return this; } //reset public final Buffer reset() {int m = mark;if (m < 0)throw new InvalidMarkException();position = m;return this; }8.position(int newPosition);?
9.limit(int newLimit);?
postion(int newPosition):position = newPosition?
limit(int newLimit):limit = newLimit;
打印的log
after create capacity: 20 ,limit: 20 ,position: 0 ,mark: -1 after position capacity: 20 ,limit: 20 ,position: 1 ,mark: -1 after limit capacity: 20 ,limit: 10 ,position: 1 ,mark: -1源碼
//position(int newPosition) public final Buffer position(int newPosition) {if ((newPosition > limit) || (newPosition < 0))throw new IllegalArgumentException("Bad position " + newPosition + "/" + limit);position = newPosition;if (mark > position) mark = -1;return this; } //limit(int newLimit) public final Buffer limit(int newLimit) {if ((newLimit > capacity) || (newLimit < 0))throw new IllegalArgumentException();limit = newLimit;if (position > limit) position = limit;if (mark > limit) mark = -1;return this; }10,remaining?
11,hasRemaining?
remaining:返回剩余的個數?
hasRemaining:返回是否還有剩余
打印的log
after create capacity: 20 ,limit: 20 ,position: 0 ,mark: -1 remaining:20 hasRemaining:true源碼
//remaining public final int remaining() {return limit - position; } //hasRemaining public final boolean hasRemaining() {return position < limit; }12,wrap(byte[] byte)?
byte變成ByteBuffer: 共用一套的數據,相當于allocate and put,不影響標記量
打印log
after capacity: 10 ,limit: 10 ,position: 0 ,mark: -1源碼
public static ByteBuffer wrap(byte[] array) {return wrap(array, 0, array.length); } //return HeapByteBuffer public static ByteBuffer wrap(byte[] array,int offset, int length) {try {return new HeapByteBuffer(array, offset, length);} catch (IllegalArgumentException x) {throw new IndexOutOfBoundsException();} } //array = hb ByteBuffer(int mark, int pos, int lim, int cap, byte[] hb, int offset) {super(mark, pos, lim, cap, 0);this.hb = hb;this.offset = offset; }13,put(byte[] byte),將byte的數組放進bytebuffer,相當于byte.length次數往bytebuffer添加byte[index],影響position的位置。
ByteBuffer heapByteBuffer = ByteBuffer.allocate(20); byte[] buffer = new byte[]{1, 2, 3, 4, 6, 7, 8, 9}; heapByteBuffer.put(buffer); printField("after put",heapByteBuffer);打印的log
after put capacity: 20 ,limit: 20 ,position: 8 ,mark: -1源碼
public final ByteBuffer put(byte[] src) {return put(src, 0, src.length); }public ByteBuffer put(byte[] src, int offset, int length) {checkBounds(offset, length, src.length);if (length > remaining())throw new BufferOverflowException();int end = offset + length;for (int i = offset; i < end; i++)this.put(src[i]);return this; }14,get(byte[] byte)?
取數據,放入到byte數組里面,數組之間不影響,相當于多次的get的操作,影響的position的位置。
打印的log
after put capacity: 20 ,limit: 20 ,position: 8 ,mark: -1 after rewind capacity: 20 ,limit: 20 ,position: 0 ,mark: -1 after get capacity: 20 ,limit: 20 ,position: 20 ,mark: -1 12346789000000000000源碼
public ByteBuffer get(byte[] dst) {return get(dst, 0, dst.length); }public ByteBuffer get(byte[] dst, int offset, int length) {checkBounds(offset, length, dst.length);if (length > remaining())throw new BufferUnderflowException();int end = offset + length;for (int i = offset; i < end; i++)dst[i] = get();return this; }15,put(int index,byte b)?
16,get(int index)?
去或者放index位置的值,注意此時不影響position的位置
打印的log
after put(index): capacity: 20 ,limit: 20 ,position: 0 ,mark: -1 2 after get(index): capacity: 20 ,limit: 20 ,position: 0 ,mark: -1源碼分析
//put(int index, byte b); public ByteBuffer put(int i, byte x) {if (isReadOnly) {throw new ReadOnlyBufferException();}//checkIndex() not nextIndexhb[ix(checkIndex(i))] = x;return this; } //get(int index) public byte get(int i) {//chekIndex not nextIndexreturn hb[ix(checkIndex(i))]; }17,slice?
復制有限區域段的byteBuffer,即position到limit的位置。返回的ByteBuffer的position=1,mark=-1,limit=capaticy =src.remaining,并且兩個byteBuffer里面的數組相互影響
打印的log
after warp capacity: 20 ,limit: 20 ,position: 0 ,mark: -1 after slice capacity: 10 ,limit: 10 ,position: 0 ,mark: -1 567891011121314 31 31源碼分析
public ByteBuffer slice() {return new HeapByteBuffer(hb,-1,0,remaining(),remaining(),position() + offset,isReadOnly); } //-1 = mark 0 = position //limit = capitity = remaining() //offset = position()+offset protected HeapByteBuffer(byte[] buf,int mark, int pos, int lim, int cap,int off, boolean isReadOnly) {super(mark, pos, lim, cap, buf, off);this.isReadOnly = isReadOnly; }18,duplicate?
復制的操作,包括所有的標示浮,并且兩個ByteBuffer的內存的數組是共同的。
打印的log
after warp capacity: 20 ,limit: 20 ,position: 0 ,mark: -1 heapByteBuffer capacity: 20 ,limit: 15 ,position: 5 ,mark: 0 duplicate capacity: 20 ,limit: 15 ,position: 5 ,mark: 0 01234567891011121314 31 31源碼分析
//mark = markValue,position= position //limit = limit(),capacity= capacity() public ByteBuffer duplicate() {return new HeapByteBuffer(hb,markValue(),position(),limit(),capacity(),offset,isReadOnly); }19,array?
將ByteBuffer轉成一個數組,相比get(byte[]b)而言,這兩個數組相互影響,但不影響position 的位置。
打印的log
after warp capacity: 20 ,limit: 20 ,position: 0 ,mark: -1 heapByteBuffer capacity: 20 ,limit: 15 ,position: 5 ,mark: 0 012345678910111213141516171819 31 31源碼分析
public final byte[] array() {if (hb == null)throw new UnsupportedOperationException();if (isReadOnly)throw new ReadOnlyBufferException();return hb; }20,compact?
將positon到limit的內容復制到0~(limit-position)的位置上,并且pisition=limit-position,limit = capatity()
打印的log
after warp capacity: 20 ,limit: 20 ,position: 0 ,mark: -1 heapByteBuffer capacity: 20 ,limit: 20 ,position: 10 ,mark: -1 56789101112131410111213141516171819源碼分析
public ByteBuffer compact() {if (isReadOnly) {throw new ReadOnlyBufferException();}// 從position開始復制到remaining位置System.arraycopy(hb, ix(position()), hb, ix(0), remaining());//postion=remaining();position(remaining());//limit=capacity()limit(capacity());discardMark();return this;}21.order?
22.getInt()/getLong()等?
內存中的數據有高序和低序之分的,那么不同的排序,輸出的結果也是不同的,同樣ByteBuffer中的字節也是有排序的,簡稱大端和小端排序,通過order來控制數據排序。?
我們知道byte占一個子節,int占4個子節,那么就意味著,如果getInt(),則需要byteBuffer中一次取4個子節。這樣就能保證取出的是int的數值,
打印的log
66051 67438087 134810123 202182159 269554195解釋下:?
66051 = 0*256*256*256+1*256*256+2*256+3 //0123?
67438087 = 4*256*256*256+5*256*256+6*256+7 //4567?
134810123 = 8*256*256*256+9*256*256+10*256+11 //891011?
…
如果將order的順序改成ByteOrder.LITTLE_ENDIAN?
代碼如下
打印的log
order capacity: 20 ,limit: 20 ,position: 0 ,mark: -1 50462976 117835012 185207048 252579084 319951120解釋下:?
50462976 = 3*256*256*256+2*256*256+1*256+0;//3210?
117835012 = 7*256*256*256+6*256*256+5*256+4;//7654?
…?
源碼的分析
23,asInterBuffer/asLongBuffer?
轉化成IntBuffer或者其他基本數據的Buffer,并且共享一塊數組區域
打印的log
intBuffer capacity: 20 ,limit: 20 ,position: 0 ,mark: -1 66051 67438087 134810123 202182159 269554195 001045678910111213141516171819源碼分析
public IntBuffer asIntBuffer() {//size/4int size = this.remaining() >> 2;int off = position();//ByteBufferAsIntBuffer 是InterBufferreturn (IntBuffer) (new ByteBufferAsIntBuffer(this,-1,0,size,size,off,order())); }和其他的類常見操作
1,File?
創建一個FileChanel
讀數據
fc.read(byteBuffer); byteBuffer.flip();寫數據
fc.write(byteBuffer); byteBuffer.clear; fc.close;簡單的例子 copy的操作
File readFile = new File("bytebuffertest/read.txt"); File outFile = new File("bytebuffertest/write.txt"); try {FileChannel readChannel = new FileInputStream(readFile).getChannel();ByteBuffer readBuffer = ByteBuffer.allocate(2);FileChannel outChannel = new FileOutputStream(outFile).getChannel();while (readChannel.read(readBuffer) >= 0) {readBuffer.flip();System.out.print(Charset.forName("utf-8").decode(readBuffer));readBuffer.flip();outChannel.write(readBuffer);readBuffer.clear();} } catch (FileNotFoundException e) {e.printStackTrace(); } catch (IOException e) {e.printStackTrace(); }打印log
hello read i cam come from read.text,want to copy write.txts同時read.txt的內容轉到了write.txt.
2,Socket?
創建一個SocketChanel
寫數據
socketChannel.write(buffer);讀數據
int bytesReaded=socketChannel.read(buffer);這里就不舉例子了。
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎
總結
以上是生活随笔為你收集整理的ByteBuffer的使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 无线无卡如何和无线路由器直连无线网卡上网
- 下一篇: 电脑参数怎么看如何查看电脑的功率