Java ByteBuffer 转字符串 [英] Java ByteBuffer to String

查看:51
本文介绍了Java ByteBuffer 转字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以这种方式将ByteBuffer转换为String是否正确,

Is this a correct approach to convert ByteBuffer to String in this way,

String k = "abcd";
ByteBuffer b = ByteBuffer.wrap(k.getBytes());
String v = new String(b.array());

if(k.equals(v))
    System.out.println("it worked");
else
    System.out.println("did not work");

我问的原因是这看起来太简单了,而其他方法如 Java:从 ByteBuffer 和相关问题转换 String 和相关问题 看起来更复杂.

The reason I ask is that is this looks too simple, whereas other approaches like Java: Converting String to and from ByteBuffer and associated problems looks more complex.

推荐答案

有一种更简单的方法可以将 ByteBuffer 解码为 String 而不会出现任何问题,由 Andy Thomas 提到.

There is simpler approach to decode a ByteBuffer into a String without any problems, mentioned by Andy Thomas.

String s = StandardCharsets.UTF_8.decode(byteBuffer).toString();

这篇关于Java ByteBuffer 转字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆