Buffer的重要屬性 position/limit/capacity

 1 package nio;  2 
 3 import java.nio.IntBuffer;  4 
 5 /**
 6  * Buffer的重要屬性 position/limit/capacity  7  * position:buffer當前所在的操做位置  8  * limit:buffer最大的操做位置  9  * capacity:buffer的最大長度 10  */
11 public class NioTest2 { 12 
13     public static void main(String[] args) { 14 
15         IntBuffer intBuffer = IntBuffer.allocate(10); 16 
17         /**
18  * 因爲bufer剛分配,此時是寫模式,因此: 19  * position = 0 20  * limit = 10 21  * capacity = 10 22          */
23  System.out.println(intBuffer.position()); 24  System.out.println(intBuffer.limit()); 25  System.out.println(intBuffer.capacity()); 26         System.out.println("----------------------------------"); 27 
28         int i; 29         for(i = 0; i < 4; i++) { 30  intBuffer.put(i); 31  } 32 
33  intBuffer.flip(); 34 
35         /**
36  * bufer寫入了4個數據,此時切換到了讀模式,因此: 37  * position = 0 38  * limit = 4 39  * capacity = 10 40          */
41  System.out.println(intBuffer.position()); 42  System.out.println(intBuffer.limit()); 43  System.out.println(intBuffer.capacity()); 44         System.out.println("----------------------------------"); 45 
46  intBuffer.clear(); 47         /**
48  * bufer清空了,可是裏面的數據是不會清空的,只是把指針重置了, 49  * 因此,這個時候buffer的指針又回到了初始狀態 50  * get(2) = 2 51  * position = 0 52  * limit = 10 53  * capacity = 10 54          */
55         System.out.println(intBuffer.get(2)); 56  System.out.println(intBuffer.position()); 57  System.out.println(intBuffer.limit()); 58  System.out.println(intBuffer.capacity()); 59         System.out.println("----------------------------------"); 60 
61  } 62 
63 }
相關文章
相關標籤/搜索