參考:Java NIO Buffer
Once you need to read the data, you need to switch the buffer from writing mode into reading mode using the flip() method call
Once you have read all the data, you need to clear the buffer, to make it ready for writing again. You can do this in two ways: By calling or by calling compact().
- clear() :clears the whole buffer
- compact():only clears the data which you have already read. Any unread data is moved to the beginning of the buffer, and data will now be written into the buffer after the unread data.
三個ByteBuffer屬性(可參考下面的圖來理解):
The meaning of position and limit depends on whether the Buffer is in read or write mode. Capacity always means the same, no matter the buffer mode.
- capacity
代表ByteBuffer的容量大小,一但滿了除非將他清空或是read,不然無法繼續寫入資料 - position
- write mode:起始時position index為0,隨者每一次寫入資料position位置都會變動,如寫了1byte則postion會index+1,index最多不能超過capacity -1
- limit write mode:代表共可寫入多少資料量,在此模式中香等於capacity
read mode:代表共有多少資料量可讀取,當使用flip()將操作模式由write改為read,
limit會被設置於position的目前所在位置
ByteBuffer buf = ByteBuffer.allocate(48);
其中的int參數就是代表欲建立的capacity大小。
沒有留言:
張貼留言