java中ByteBuffer和String相互转换

java提供了缓冲类,在很多编解码和网络请求中会用到,其中ByteBuffer和String类型可以互相转换,代码如下:

Charset charset = StandardCharsets.UTF_8;
String str = "Hello world";
ByteBuffer buffer = ByteBuffer.allocate(1024);
//	将字符串转成ByteBuffer
buffer.put(str.getBytes(StandardCharsets.UTF_8));
//	将ByteBuffer转成字符串1
buffer.flip();
String s = charset.decode(buffer).toString();
System.out.println(s);
//	将ByteBuffer转成字符串2
buffer.flip();
String s1 = new String(buffer.array(), buffer.position(), buffer.limit(), StandardCharsets.UTF_8);
System.out.println(s1);