其他分享
首页 > 其他分享> > String与ByteBuffer互转

String与ByteBuffer互转

作者:互联网

import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

public class Test {
    public static void main(String[] args) {
        String str = "hello word";
        ByteBuffer byteBuffer = ByteBuffer.wrap(str.getBytes(StandardCharsets.UTF_8));

        byte[] bytes = byteBuffer.array();
        String str_x = new String(bytes, 0, bytes.length);

        Charset charset = Charset.forName("utf-8");
        String str_y = charset.decode(byteBuffer).toString();

        System.out.println(str_x + "    " + str_y);
    }
}

 

标签:Charset,String,charset,str,互转,ByteBuffer,nio
来源: https://blog.csdn.net/weixin_42414567/article/details/121559144