2013年7月27日 星期六

Java NIO - ByteBuffer基本屬性介紹 capacity、limit、position


參考: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().

  1. clear() :clears the whole buffer
  2. 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實際上操作方式為:先write再read

三個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.




  1. capacity
    代表ByteBuffer的容量大小,一但滿了除非將他清空或是read,不然無法繼續寫入資料
  2. position
    1. write mode:起始時position index為0,隨者每一次寫入資料position位置都會變動,如寫了1byte則postion會index+1,index最多不能超過capacity -1
              read mode:當使用flip()將操作模式由write改為read,position會自動被reset至0,然               後隨者每一次read資料量不同position位置將會自動前進
  1. limit
  2.          write mode:代表共可寫入多少資料量,在此模式中香等於capacity      
             read mode:代表共有多少資料量可讀取,當使用flip()將操作模式由write改為read,
             limit會被設置於position的目前所在位置
建立一個ByteBuffer使用allocate:
ByteBuffer buf = ByteBuffer.allocate(48);
其中的int參數就是代表欲建立的capacity大小。


相關function使用方式待續....

沒有留言:

張貼留言