[英]How to find out total number of bytes stored in ByteBuffer?
我試圖提取我存儲在ByteBuffer data_record_value
總字節數。
下面是我們如何將data_record_value
表示為一個字節數組,然后從Java代碼寫入我們的數據庫。
Offset Length (in bytes) Purpose
0 2 - clientId byte array
2 8 - value of lastModifiedDate
2+8 4 - length of avroBinaryValue array
2+8+4 Y - avroBinaryValue array
這就是我從數據庫中提取它的方式 -
ByteBuffer data_record_value = r.getBytes("data_record_value");
// now how do I extract total number of bytes I have stored in data_record_value?
在做了一些研究之后,我發現了多種方法來提取我的ByteBuffer data_record_value
存儲的字節data_record_value
,我不確定哪一個是對的?
第一種方式是:
byte[] b = new byte[data_record_value.remaining()];
record_value.get(b);
// this will be in bytes right?
System.out.println("Byte Array Length: " + b.length);
第二種方式是:
int numberOfBytesInRecord = data_record_value.limit();
第三種方式是:
int numberOfBytesInRecord = data_record_value.remaining();
但是上述所有方式的數字完全不相符? 我不確定應該使用哪一個? 我需要提取data_record_value
存儲的總字節數。
要進行交叉檢查,我們可以從data_record_value
ByteBuffer中提取單個字段,並計算我們存儲的總字節數,並與上述任何方法進行比較。
// clientId (of two bytes by using short)
short extractClientId = data_record_value.getShort();
// lastModifiedDate ( of 8 bytes which can be long )
long extractLastModifiedDate = data_record_value.getLong();
int extractAvroBinaryValueLength = data_record_value.getInt();
byte[] extractAvroBinaryValue = new byte[extractAvroBinaryValueLength];
data_record_value.get(extractAvroBinaryValue); // read attributeValue from the remaining buffer
System.out.println(extractClientId);
System.out.println(extractLastModifiedDate);
System.out.println(new String(extractAvroBinaryValue));
更新: -
在其中一個ByteBuffer data_record_value
,這是我打印出來的 -
System.out.println("Record Value Capacity: " + data_record_value.capacity());
System.out.println("Record Value Position: " + data_record_value.position());
System.out.println("Record Value Limit: " + data_record_value.limit());
System.out.println("Record Value Remaining: " + data_record_value.remaining());
System.out.println("Record Value: " + data_record_value);
這就是打印出來的 -
Record Value Capacity: 387
Record Value Position: 185
Record Value Limit: 250
Record Value Remaining: 65
Record Value: java.nio.HeapByteBuffer[pos=185 lim=250 cap=387]
使用ByteBuffer
,從緩沖區中輸入和獲取值之間存在差異。
當字節放在緩沖區上時,它們會被添加到當前位置。 如果達到限制,則緩沖區已滿。 因此position()
顯示緩沖區中的數據量,而remaining()
顯示仍可以在緩沖區上放置多少字節。 我在這里假設要考慮的數據從位置0開始(通常應該是這種情況)。
當從緩沖區中檢索字節時,緩沖區通常已被“翻轉”。 這意味着該位置設置為0,並且該限制設置為舊位置。 現在, position()
返回的值顯示已經檢索了多少字節, remaining()
顯示了尚未檢索的字節數。
在您的示例中,您將返回一個預先存在的緩沖區。 數據庫將數據放入此緩沖區,並將位置放在數據的位置,將限制放在數據結束后的字節處。 因此,數據庫將數據放入緩沖區,然后翻轉緩沖區。
如果position()
未設置為0,則數據庫可以使用更高級的方案來緩沖數據,但是位置在數據的開頭和最后的限制的想法保持不變。
因此,在使用相對get方法從緩沖區檢索任何數據之前 , ByteBuffer.remaining()
將返回緩沖區中的數據總量。
一旦開始檢索信息,這些信息就會丟失(盡管當然有獲取信息的方法,例如使用mark()
和reset()
)。 如果您在此過程中稍后需要此信息,則只需將其存儲在本地變量或字段中:
int received = buffer.remaining();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.