ByteBuffer和String互转

satuo20 1年前 ⋅ 211 阅读
       Charset charset = StandardCharsets.UTF_8;
       String str = "字符串----------------abc";
       ByteBuffer buffer = ByteBuffer.allocate(1024);
       //将字符串转成ByteBuffer
       buffer.put(str.getBytes(charset));
       //切换读取数据的模式
       buffer.flip();
       //----将ByteBuffer转成字符串1------------------------------------------------------------------------------
       String string1 = charset.decode(buffer).toString();
       System.out.println(string1);
       //----将ByteBuffer转成字符串2------------------------------------------------------------------------------
       buffer.flip();
       String string2 = new String(buffer.array(), 0, buffer.limit());
       System.out.println(string2);

全部评论: 0

    我有话说: