java – 如何从ByteBuffer获取used byte []

java.nio.ByteBuffer类有一个ByteBuffer.array()方法,但是这会返回一个数组,该数组是缓冲区容量的大小,而不是已用容量.因此,我遇到了很多问题.

我注意到使用ByteBuffer.remaining()给了我缓冲区当前正在使用的字节数,所以基本上我正在寻找的是获取只使用字节的byte []的方法. (即,ByteBuffer.remaining()中显示的字节.

我尝试了一些不同的东西,但我似乎失败了,唯一的解决方法是我能想到它创建另一个ByteBuffer并分配剩余缓冲区的大小,然后写入(x)字节.

解决方法:

从读取Javadocs开始,我认为只剩下当前位置和限制之间的字节数.

remaining()

Returns the number of elements between the current position and the limit.

此外:

A buffer’s capacity is the number of elements it contains. The capacity of a buffer is never negative and never changes.

A buffer’s limit is the index of the first element that should not be read or written. A buffer’s limit is never negative and is never greater than its capacity.

A buffer’s position is the index of the next element to be read or written. A buffer’s position is never negative and is never greater than its limit.

所以考虑到这一点:

static byte[] getByteArray(ByteBuffer bb) {
    byte[] ba = new byte[bb.limit()];
    bb.get(ba);
    return ba;
}

这使用了ByteBuffer的get(byte [] dst)方法

public ByteBuffer get(byte[] dst)

Relative bulk get method.
This method transfers bytes from this buffer into the given destination array. An invocation of this method of the form src.get(a) behaves in exactly the same way as the invocation

06001

上一篇:Java NIO系列教程(四) Scatter/Gather


下一篇:java – 当缓冲区未满时,为什么bytebuffer会给出缓冲区溢出异常