简体   繁体   English

是否可以从List创建ByteBuffer <ByteBuffer> ?

[英]Is it possible to create ByteBuffer from a List<ByteBuffer>?

Let's say i have a list/arrayList or an array of ByteBuffers ( List<ByteBuffer> or ByteBuffer[] ) 假设我有一个list / arrayList或ByteBuffers数组( List<ByteBuffer>ByteBuffer[]

It is possible from this to directly get the bytes from the above array without iterating through all the items or computing their total size? 从中可以直接从上面的数组中获取字节而不迭代所有项目或计算它们的总大小? I am looking for something like this: 我正在寻找这样的东西:

ByteBuffer[] bufferList = new ByteBuffer[7]; //this can be any kind of list of ByteBuffers
//add items to the array
ByteBuffer buffer = (ByteBuffer) bufferList; //what i want to achieve  

Of course the last line is not correct. 当然最后一行不正确。

The thing is that i already have in the array all the bytes in order, but I want them not to be in a list anymore, but in a single ByteBuffer. 问题是我已经在数组中按顺序包含所有字节,但是我希望它们不再在列表中,而是在单个ByteBuffer中。 So is there something that makes possible to create a ByteBuffer from a list/array of ByteBuffers? 那么是否有可能从ByteBuffers的列表/数组创建ByteBuffer?

Thank you! 谢谢!

public ByteBuffer convertToOne(ByteBuffer[] src)
{
    int size=0;
    for(int i = 0 ; i < src.length ; i++) {
        size+=src[i].array().length;
    }

    ByteBuffer newBuffer = ByteBuffer.allocate(size);

    int sizeAt = 0;
    for(int i = 0 ; i < src.length ; i++) {
        newBuffer.put(src[i].array(), sizeAt);
        sizeAt += src[i].array().length;
    }
    return newBuffer;
}

I believe you're going to have to create a new ByteBuffer and copy each of the buffers in bufferList into the new one. 我相信你将不得不创建一个新的ByteBuffer并将bufferList每个缓冲区bufferList到新的缓冲区中。 You should put this functionality in a method so as to not repeat the code each time you use it. 您应该将此功能放在方法中,以便每次使用时都不重复代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM