简体   繁体   English

Java中的可变字节数组

[英]Variable byte array in java

I am reading a binary file that has structure : 我正在读取具有以下结构的二进制文件:

(integer)(byte[]) (整数)(字节[])

The integer represents the size of the byte array that comes next. 整数表示下一个字节数组的大小。 To avoid allocate all time a byte array, i just allocate when the size of the next read is greater than the last one. 为了避免一直分配一个字节数组,我只在下一次读取的大小大于最后一次读取的大小时进行分配。

int sz = rawBuffer.getInt();
if (sz > lSz){  //lSz is a class variable
   buffer = new byte[sz];
   lSz = sz;
}
rawBuffer.get(buffer, 0, sz);

The problem is that the buffer has always the maximum size. 问题在于缓冲区始终具有最大大小。 If a read a byte array of size 5 and the a byte array of size 3, the buffer.length is going to be 5. 如果读取大小为5的字节数组和大小为3的字节数组,则buffer.length将为5。

Is there anyway to resize the buffer, without need to realocate? 无论如何,是否有必要调整缓冲区的大小而无需重新分配? Or is it better to have another structure that holds the efective size of the array, like a ByteBuffer for example. 或者拥有另一个保持数组有效大小的结构更好,例如ByteBuffer。

I don't think there would be a way to resize the buffer without the process of reallocation. 我认为没有重新分配过程就不会有一种方法来调整缓冲区的大小。 So if the size of the buffer is critical for you, you can try changing your 因此,如果缓冲区的大小对您至关重要,则可以尝试更改

if (sz > lSz){  //lSz is a class variable
   buffer = new byte[sz];
   lSz = sz;
}

to

if (sz != lSz){
   buffer = new byte[sz];
   lSz = sz;
}

Good Luck. 祝好运。

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

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