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);
    }
}

String与ByteBuffer互转

 

上一篇:Java8常用的内置函数式接口(一)Predicate、Consumer、Supplier、Function


下一篇:html基础