2013年7月30日 星期二

Java NIO - Buffer基本function介紹flip()、rewind()、clear()、compact()、mark()、reset()


參考:Java NIO Buffer
搭配此範例圖參考:

Write data to a Buffer:
  1. Write data from a Channel into a Buffer:
    int bytesRead = inChannel.read(buf); //read into buffer.
  2. 自行使用put()之類的方式寫入
    buf.put(127);
Reading data from a Buffer:
  1. Read data from the buffer into a channel.
     
    //read from buffer into channel.
    int bytesWritten = inChannel.write(buf);
    
  2. 自行使用get()之類的方式讀取:
     
    byte aByte = buf.get();
    
  • flip()
    將Butter由write mode轉變為read moode,並將
    (1)limit設為當前position位置
    (2)position reset to 0
  • rewind()
    將position設定回0,但limit保持不變,因此可重新read所有的資料

  • clear()與compact():
  • clear()
    將position設定回0,limit設定至capacity,然而Buffer中資料並不是真的被清除,只是將這些mark改變,讓我們可以有足夠的空間重新寫入資料。但是請注意,雖然資料沒有被清除,但是因為mark被重置了,因此unread的資料將無法再次被讀取,若目前尚有未讀取資料但又需要在讀取之前write data,則可使用compact()代替clear()
  • compact()

  • mark()與reset():
  • mark():使用mark()則可將目前的position做標記(mark)
  • reset():將position 設定回之前所設定的標記(mark)處
buffer.mark();
//call buffer.get() a couple of times, e.g. during parsing.
buffer.reset();  //set position back to mark.

equals()與compareTo():


  • equals():滿足以下條件則2個buffer代表equals
    (1)type相同(char、byte、int etc..)
    (2)剩餘的【未讀】buffer大小(byte)相同,
    (3)剩餘的【未讀】buffer內容皆相同
    如上所述,equals()只比較剩餘【未讀】的buffer內容,並非整個buffer的內容
  • compareTo():與equals()相同,只比較剩餘的【未讀】buffer內容,通常做為排序使用;符合以下的情況代表【smaller】:
    (1)
    (2)所有的內容皆相同,但擁有較少的內容(?)

沒有留言:

張貼留言