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 }
相关文章
相关标签/搜索