学无先后,达者为师

网站首页 java综合 正文

Java基础之String与ByteBuffer互转

作者:左耳听过流年的声 更新时间: 2022-01-23 java综合
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);
    }
}

原文链接:https://blog.csdn.net/weixin_42414567/article/details/121559144

栏目分类
最近更新