以这种方式将ByteBuffer转换为字符串是正确方法吗,
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: Converting String to and from ByteBuffer and associated problems,看起来更复杂。
发布于 2016-10-04 14:01:33
安迪·托马斯提到过,有一种更简单的方法可以毫无问题地将ByteBuffer
解码为String
。
String s = StandardCharsets.UTF_8.decode(byteBuffer).toString();
发布于 2013-06-28 07:34:14
试试这个:
new String(bytebuffer.array(), "ASCII");
注意:在不知道其编码的情况下,无法正确地将字节数组转换为字符串。
我希望这能帮到你
发布于 2015-06-16 06:52:06
我只想指出,假设ByteBuffer.array()总是有效是不安全的。
byte[] bytes;
if(buffer.hasArray()) {
bytes = buffer.array();
} else {
bytes = new byte[buffer.remaining()];
buffer.get(bytes);
}
String v = new String(bytes, charset);
通常,buffer.hasArray()总是真或假,这取决于您的用例。在实践中,除非你真的希望它在任何情况下都能工作,否则优化掉你不需要的分支是安全的。但是其余的答案可能不适用于通过ByteBuffer.allocateDirect()创建的ByteBuffer。
https://stackoverflow.com/questions/17354891
复制相似问题