e160. putting bytes into a bytebuffer.txt

来自「这里面包含了一百多个JAVA源文件」· 文本 代码 · 共 34 行

TXT
34
字号
A ByteBuffer has a capacity which determines how many bytes it contains. This capacity can never change. Any byte in the ByteBuffer can be modified using the absolute version of put(), which takes an index in the range [0..capacity-1]. 
The bytes in a ByteBuffer can also be set using the relative version of put(), which uses the position and limit properties of the buffer. In particular, this version of put() sets the byte at the position and advances the position by one. put() cannot set bytes past the limit (even though limit might be less than the capacity). The position is always <= limit and limit is always <= capacity. 

    // Create an empty ByteBuffer with a 10 byte capacity
    ByteBuffer bbuf = ByteBuffer.allocate(10);
    
    // Get the buffer's capacity
    int capacity = bbuf.capacity(); // 10
    
    // Use the absolute put().
    // This method does not affect the position.
    bbuf.put((byte)0xFF); // position=0
    
    // Set the position
    bbuf.position(5);
    
    // Use the relative put()
    bbuf.put((byte)0xFF);
    
    // Get the new position
    int pos = bbuf.position(); // 6
    
    // Get remaining byte count
    int rem = bbuf.remaining(); // 4
    
    // Set the limit
    bbuf.limit(7); // remaining=1
    
    // This convenience method sets the position to 0
    bbuf.rewind(); // remaining=7

 Related Examples 

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?