代码演示
package com.chat;
import java.nio.ByteBuffer;
public class ByteBufferDemo {
public static void main(String[] args) {
System.out.println("------初始化Buffer------");
ByteBuffer bb = ByteBuffer.allocate(10);
System.out.println("当前位置在"+bb.position());
System.out.println("限制位置在"+bb.limit());
System.out.println("容量是"+bb.capacity());
System.out.println("------put之后------");
String str ="Hello";
byte[] bytes = str.getBytes();
bb.put(bytes);
System.out.println("当前位置在"+bb.position());
System.out.println("限制位置在"+bb.limit());
System.out.println("容量是"+bb.capacity());
System.out.println("------调用flip之后------");
bb.flip();
System.out.println("当前位置在"+bb.position());
System.out.println("限制位置在"+bb.limit());
System.out.println("容量是"+bb.capacity());
char ch;
while (bb.hasRemaining())
{
ch =(char)bb.get();
System.out.print(ch);
}
}
}
- 我们调用ByteBuffer的allocate方法新建Buffer,新建完成后当前位置为0,限制位置为容量大小。
- 当Put进元素之后当前位置变为put元素长度对应的位置,限制位置不变。
- 调用flip方法之后限制位置变成当前位置,随后将当前位置重置。变为可读模式