方法一:
ByteBuf buf = Unpooled.copiedBuffer("我看行", CharsetUtil.UTF_8);
System.out.println("result:"+new String(buf.array()));
方法二:
ByteBuf buf = Unpooled.copiedBuffer("我看行", CharsetUtil.UTF_8);
byte[] bytes = new byte[buf.readableBytes()];
ByteBuf buf1 = buf.getBytes(buf.readerIndex(), bytes);
System.out.println("result:"+new String(buf1.array()));
方法三(可以对字节进行处理,读完后指针变化了):
ByteBuf buf = Unpooled.copiedBuffer("我看行", CharsetUtil.UTF_8);
byte[] bytes = new byte[buf.readableBytes()];
int i = 0;
while (buf.isReadable()) {
bytes[i] = buf.readByte();
i ++;
}
System.out.println("result:"+new String(bytes));
方法四(不改变指针位置):
ByteBuf buf = Unpooled.copiedBuffer("我看行", CharsetUtil.UTF_8);
byte[] bytes = new byte[buf.readableBytes()];
for (int i = buf.readerIndex();i < buf.readableBytes();i++){
bytes[i] = buf.getByte(i);
}
System.out.println("result:"+new String(bytes));
1 可以通过main方法或者写一个单元测试
2 通过静态方法获取bytBuf
3 将byte存入缓冲区
4 将结果封装为String 进行打印
@Test
public void testCode1() {
//首先分配内存空间
ByteBuffer buffer = ByteBuffer.allocate(102400);
String sg=new String("i like java");
byte[] bytes=sg.getBytes();
//将数据存储在缓冲去
buffer=ByteBuffer.wrap(bytes);
System.out.println("\t" + new String(buffer.array()));
}