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 }