字符串转ByteBuf
时间: 2023-10-16 13:06:09 浏览: 88
字符串转换
字符串转换为ByteBuf是通过将字符串转换为ByteBuffer,然后再将ByteBuffer转换为ByteBuf实现的。
示例代码如下:
```java
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import java.nio.charset.StandardCharsets;
public class TestStringToByteBuf {
public static void main(String[] args) {
String str = "Hello, world!";
// 字符串转为 ByteBuffer
byte[] bytes = str.getBytes(StandardCharsets.UTF_8);
ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
// ByteBuffer 转为 ByteBuf
ByteBuf byteBuf = Unpooled.wrappedBuffer(byteBuffer);
System.out.println("字符串转为 ByteBuf: " + byteBuf.toString(StandardCharsets.UTF_8));
}
}
```
阅读全文