2012-08-24 37 views
0

我目前使用的是Java字節緩衝區的Java字節緩衝區填滿完全

ByteBuffer batch = ByteBuffer.allocate(tuple_size * batch_size) ; 
    int pos = 0; 
    int sent = 0; 
    while (sent++ < batch_size) { 
      Event event = (Event) it.next(); 
      batch.put(event.getData(), pos, tuple_size); 
      pos += tuple_size; 

     } 
    return batch.array(); 

目前的batch_size設置爲2。我的問題是,在第二輪中,我得到它,我無法解釋因爲IndexOutOfBoundsException異常,打印出follwoing細節:

 System.out.println(pos + " " + batch.capacity() + " " + batch.position() + " " + batch.remaining()); 

我得到: 0 200 0 200(圓0)

100 200 100 100(第1輪)

這是人們所期望的。現在,根據文檔,似乎綁定檢查確實可以保留:

offset - The offset within the array of the first byte to be read; must be non-negative and no larger than array.length 
length - The number of bytes to be read from the given array; must be non-negative and no larger than array.length - offset 

如何完全填滿緩衝區? (同時保持底層緩衝區的長度爲tuple_size * batch_size?)

回答

2

我想你不需要pos變量。 put方法試圖讀入event.getData()的位置pos,而我認爲你想從位置0讀event.getData()。你可以簡單地使用batch.put(event.getData())來追加數組的全部內容到緩衝區。

+1

閱讀文檔,這非常合理。這不是我期望的相對投入操作的工作方式。 – Buhb

+1

不幸的是,數組沒有相對的'put()'函數。如果你需要這樣的話,你必須首先調用'position()',然後調用'put()'。 – Flavio

+0

完美。謝謝。正如Buhb所說,我並不期望以這種方式工作。但寧可抵消是相對於ByteBuffer。 – user1018513

0

從你的問題來看,如果tuple_size對於event.getData()足夠大,這是不明顯的。 如果不是,那會導致您的IndexOutofBoundsException。 也許這是關閉的?

另一種可能性是您的迭代器it只包含一個元素。

編輯:根據文檔,如果你的緩衝區空間不足,你應該得到一個BufferOverflowException。從文檔 引用:

此方法將字節從給定源 陣列這個緩衝器。如果要在此緩衝區中保留 以上的字節,則要從該陣列複製更多字節,也就是說,如果length> remaining(),則不會傳輸 字節並引發BufferOverflowException。

這表明您的問題不符合您的期望。

+0

event.getData()始終等於tuple_size,隊列始終默認包含1024個元素 – user1018513

+0

我得到一個IndexArrayOutofBound異常。不是BufferOverflowException,因爲checkBound方法失敗。但我不知道它爲什麼失敗。 – user1018513