NIO Buffer

简要记录一下Buffer对象的基本原理和操作。

重要参数

Buffer中有三个重要的参数,下面的表格描述了它们的作用和区别:

Buffer的参数表

下面的实例可以更好地帮助理解:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
public class TestBuffer {
public static void main(String[] args) {
ByteBuffer b = ByteBuffer.allocate(15);
System.out.print("After allocation done: \t");
System.out.printf("limit=%s, capacity=%d, position=%d\n", b.limit(), b.capacity(), b.position());
for (int i = 0; i < 10 ; i++) {
b.put((byte)i);
}
System.out.print("After saving 10 bytes: \t");
System.out.printf("limit=%s, capacity=%d, position=%d\n", b.limit(), b.capacity(), b.position());
b.flip();
System.out.print("After flip():\t\t\t");
System.out.printf("limit=%s, capacity=%d, position=%d\n", b.limit(), b.capacity(), b.position());
System.out.print("Reading buffer: \t\t");
for (int i = 0; i < 5; i++) {
System.out.print(b.get());
}
System.out.print("\nAfter reading 5 bytes: \t");
System.out.printf("limit=%s, capacity=%d, position=%d\n", b.limit(), b.capacity(), b.position());
b.flip();
System.out.print("After flip(): \t\t\t");
System.out.printf("limit=%2s, capacity=%d, position=%d\n", b.limit(), b.capacity(), b.position());
}
}

运行结果如下:

1
2
3
4
5
6
After allocation done: limit=15, capacity=15, position=0
After saving 10 bytes: limit=15, capacity=15, position=10
After flip(): limit=10, capacity=15, position=0
Reading buffer: 01234
After reading 5 bytes: limit=10, capacity=15, position=5
After flip(): limit= 5, capacity=15, position=0

基本操作

Buffer相关的操作有:

  1. Buffer创建
    • allocate
    • wrap
  2. 重置和清空缓冲区
    • rewind
    • clear
    • flip
  3. 读写缓冲区
    • get
    • put
  4. 标志缓冲区
    • mark
    • reset
  5. 复制缓冲区
    • duplicate
  6. 缓冲区分片
    • slice
  7. 只读缓冲区
    • asReadOnlyBuffer
  8. 文件映射到内存
    • MappedByteBuffer
  9. 处理结构化数据
    • ScatteringByteChannel
    • GatheringByteChannel

因为内容较多,这里只记录一个大纲,以后需要的时候方便检索。

参考资料