1、导入netty的jar包
使用ByteBuf必须导入下面的两个包
netty-buffer-*.*.*.Final.jar
netty-common-*.*.*.Final.jar
jar下载地址
https://netty.io/downloads.html
2、基本使用
2.1 ByteBuf初始化
ByteBuf buf = Unpooled.buffer(10);
ByteBuf newBuf = Unpooled.buffer(4);
// buf是否可读,返回boolean
buf.isReadable()
// buf是否可写,返回boolean
buf.isWritable()
// buf可以读的字节数
buf.readableBytes()
// buf可以写的字节数
writablesBytes()
// buf当前read索引
buf.readerIndex()
// buf当前write索引
buf.writerIndex()
2.2 ByteBuf写字节
ByteBuf写1个字节
方法1:writeByte(int value)
// 将value写入Buf中,写索引自动加1
buf.writeByte(value);
方法2:setByte(int index, int value)
// 更改buf的index位置的值为value
buf.setByte(index, value);
ByteBuf写多个字节
方法1:writeBytes(ByteBuf src,int srcIndex,int length)
// 从newBuf的srcIndex位置,读取length个值写入buf中,写索引自动加length
buf.writeBytes(newBuf,srcIndex,length)
方法2:setBytes(int index, ByteBuf src, int srcIndex, int length)
// 将buf中从index以后,更改为newBuf中从srcIndex的length个值,注意索引不要越界
buf.setBytes(index, newBuf, srcIndex, length)
2.3 ByteBuf读字节
ByteBuf读1字节
方法1:readByte()
// 读取ByteBuf,读索引自动加1
buf.readByte()
方法2:getByte(int index)
// 获得buf的index位置的字节
buf.getByte(index)
ByteBuf读多个字节
方法1:readBytes(ByteBuf src, long position, int length)
// 从newBuf中读取length个值,从buf的position位置处插入,读索引自动加length,注意:不要越界
newBuf.readBytes(buf, position, length)
方法2:getBytes(int index, ByteBuf src, long position, int length)
// 从buf中index位置开始读取length个字节,从newBuf的position位置写入,注意:newBuf要能足够存储length个字节
buf.getBytes(index, newBuf, position, length)
3、实例
package test;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
public class Test {
public static void main(String[] args) {
// 初始化
ByteBuf buf = Unpooled.buffer(10);
ByteBuf newBuf = Unpooled.buffer(4);
/*
for(int i=0;i<buf.capacity(); i++) {
// 写入ByteBuf,写索引自动加1
buf.writeByte(i);
// 读取ByteBuf,读索引自动加1
System.out.println(buf.readByte());
System.out.println(buf.readableBytes());
System.out.println(buf.writableBytes());
System.out.println(buf.readerIndex());
System.out.println(buf.writerIndex());
}
*/
/*
for(int j=0; j<newBuf.capacity(); j++) {
newBuf.writeByte(j);
}
// 从newBuf的1位置开始,读2个字节,写入到buf中
buf.writeBytes(newBuf, 1, 2);
// 从buf的5位置处写入,从newBuf的1位置开始的3个字节,
buf.setBytes(5, newBuf, 1, 3);
for(int j=0; j<buf.capacity(); j++) {
System.out.print(buf.getByte(j)+" ");
}
*/
/*
for(int i=0;i<newBuf.capacity(); i++) {
newBuf.writeByte(i);
}
// 从newBuf中读4个字节,从buf的5位置处插入
newBuf.readBytes(buf, 5, 2);
for(int j=0; j<buf.capacity(); j++) {
System.out.print(buf.getByte(j)+" ");
}
*/
for(int i=0;i<buf.capacity(); i++) {
buf.writeByte(i);
}
// 从buf的5位置处,开始读4个字节,从newBuf的0位置写入
buf.getBytes(5, newBuf, 0, 4);
for(int j=0; j<newBuf.capacity(); j++) {
System.out.print(newBuf.getByte(j)+" ");
}
}
}