Netty
中提供了替代 NIO
中的 ByteBuffer
池化工具类,如下所示:
package main;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.util.CharsetUtil;
import java.nio.charset.Charset;
public class UnpooledDemo1 {
public static void main(String[] args) {
/**
* public abstract byte[] array(); 是个字节数组
* 有三个参数将数组分布三部分:
* 0-readIndex 表示已经读过的数据
* readIndex—writeIndex 还可以读取的数据
* writeIndex—capacity 不能往后读取数据了
*/
ByteBuf buffer = Unpooled.buffer(10);
for (int i = 0; i < 10; i++) {
buffer.writeByte(i);
}
for (int i = 0; i < 10; i++) {
System.out.println(buffer.readByte());
}
/*************************************************/
ByteBuf buf = Unpooled.copiedBuffer("hello world", CharsetUtil.UTF_8);
if (buf.hasArray()) {
byte[] content = buf.array();
System.out.println(new String(content, Charset.forName("UTF-8")));
System.out.println(buf.arrayOffset());
System.out.println(buf.readerIndex());
System.out.println(buf.writerIndex());
System.out.println(buf.capacity());
System.out.println(buf.getByte(1));
System.out.println(buf.readByte());
System.out.println(buf.readableBytes());
int len = buf.readableBytes();
for (int i = 0; i < len; i++) {
System.out.println((char)buf.readByte());
}
}
}
}
运行结果:
0
1
2
3
4
5
6
7
8
9
hello world
0
0
11
33
101
104
10
e
l
l
o
w
o
r
l
d
Process finished with exit code 0
然后在回忆下 NIO 中同的 Buffer
类,代码如下:
public static void main1(String[] args) {
IntBuffer allocate = IntBuffer.allocate(5);
allocate.put(30);
allocate.put(34);
Buffer flip = allocate.flip();
while (flip.hasRemaining()) {
System.out.println(allocate.get());
}
}