ByteBuffer類初探

告別拖延症,跟你的小惡魔較較勁!

ByteBuffer簡介

ByteBuffer類是在Java NIO中經常使用的一個緩衝區類,使用它可以進行高效的存取操作。通過申請內存空間,作爲緩存區。ByteBuffer是個抽象的方法。

public abstract class ByteBuffer
        extends Buffer
        implements Comparable<ByteBuffer>

創建ByteBuffer對象的方法有:

這裏寫圖片描述

public static ByteBuffer allocate(int capacity) {
        if (capacity < 0)
            throw new IllegalArgumentException();
        return new HeapByteBuffer(capacity, capacity);
}  //申請capacity字節大小的內存緩衝區

ByteBuffer.get();

取出當前position的byte, 並將position加1;

private void testByteBuffer() {
        String content = "testBuffer";
        ByteBuffer byteBuffer = ByteBuffer.wrap(content.getBytes());
        Log.d(TAG, "byteBuffer's position: " + byteBuffer.position());

        byte getContent = byteBuffer.get(); // position = position + 1
        Log.d(TAG, "byteBuffer's position: " + byteBuffer.position() + " get byte: " + getContent);

        getContent = byteBuffer.get();
        Log.d(TAG, "byteBuffer's position: " + byteBuffer.position() + " get byte: " + getContent);
    }

log:

D/TestByteBufferActivity: byteBuffer’s position: 0
D/TestByteBufferActivity: byteBuffer’s position: 1 get byte: 116
D/TestByteBufferActivity: byteBuffer’s position: 2 get byte: 101

t字符對應Ascii 116, e字符對應Ascii 101

發佈了80 篇原創文章 · 獲贊 17 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章