java bytebuffer to string_Java ByteBuffer到String

Java ByteBuffer到String

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

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以及相关问题看起来更复杂。

8个解决方案

70 votes

EDIT(2018):@xinyongCheng编辑的兄弟答案是一种更简单的方法,应该是公认的答案。

如果您知道字节在平台的默认字符集中,那么您的方法将是合理的。 在您的示例中,这是正确的,因为ByteBuffer.array()返回平台的默认字符集中的字节。

更常见的是,您需要指定编码。 但是,与您链接的问题相比,有一种更简单的方法。 String API提供了在特定编码中在String和byte []数组之间进行转换的方法。 当需要更多地控制解码[编码]过程时,这些方法建议使用CharsetEncoder / CharsetDecoder。“

要从特定编码中的String获取字节,可以使用兄弟getBytes()方法:

byte[] bytes = k.getBytes( StandardCharsets.UTF_8 );

要将具有特定编码的字节放入String,可以使用不同的String构造函数:

String v = new String( bytes, StandardCharsets.UTF_8 );

请注意,ByteBuffer.array()是可选操作。 如果您使用数组构造了ByteBuffer,则可以直接使用该数组。 否则,如果您想要安全,请使用ByteBuffer.get(byte[] dst, int offset, int length)将缓冲区中的字节转换为字节数组。

Andy Thomas answered 2019-07-26T01:46:14Z

61 votes

有一种更简单的方法可以将ByteBuffer解码成String而没有任何问题,Andy Thomas提到了这一点。

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

xinyong Cheng answered 2019-07-26T01:46:38Z

16 votes

试试这个:

new String(bytebuffer.array(), "ASCII");

NB。 你不能正确地将字节数组转换为字符串而不知道它的编码。

我希望这有帮助

Dan Bray answered 2019-07-26T01:47:06Z

11 votes

只是想指出,假设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()将始终为true或false,具体取决于您的用例。 在实践中,除非您真的希望它在任何情况下都能工作,否则可以安全地优化您不需要的分支。 但其余的答案可能不适用于通过ByteBuffer.allocateDirect()创建的ByteBuffer。

Fuwjax answered 2019-07-26T01:47:39Z

5 votes

简单地调用array()的答案并不完全正确:当缓冲区已被部分消耗,或者指的是数组的一部分时(你可以在一个给定的偏移处,而不是从头开始),我们必须 在我们的计算中说明了这一点。 这是适用于所有情况下缓冲区的通用解决方案(不包括编码):

if (myByteBuffer.hasArray()) {

return new String(myByteBuffer.array(),

myByteBuffer.arrayOffset() + myByteBuffer.position(),

myByteBuffer.remaining());

} else {

final byte[] b = new byte[myByteBuffer.remaining()];

myByteBuffer.duplicate().get(b);

return new String(b);

}

有关编码的问题,请参阅Andy Thomas的回答。

Alex Yarmula answered 2019-07-26T01:48:11Z

1 votes

注意(除了编码问题),一些更复杂的代码链接会导致问题的ByteBuffer的“活动”部分(例如通过使用位置和限制),而不是简单地编码所有字节 在整个后备阵列中(这些答案中的许多例子都是这样)。

Jas answered 2019-07-26T01:48:37Z

1 votes

将String转换为ByteBuffer,然后使用Java将ByteBuffer转换回String:

import java.nio.charset.Charset;

import java.nio.*;

String babel = "obufscate thdé alphebat and yolo!!";

System.out.println(babel);

//Convert string to ByteBuffer:

ByteBuffer babb = Charset.forName("UTF-8").encode(babel);

try{

//Convert ByteBuffer to String

System.out.println(new String(babb.array(), "UTF-8"));

}

catch(Exception e){

e.printStackTrace();

}

首先打印打印的裸字符串,然后将ByteBuffer转换为array():

obufscate thdé alphebat and yolo!!

obufscate thdé alphebat and yolo!!

这对我有帮助,将字符串减少到原始字节可以帮助检查发生了什么:

String text = "こんにちは";

//convert utf8 text to a byte array

byte[] array = text.getBytes("UTF-8");

//convert the byte array back to a string as UTF-8

String s = new String(array, Charset.forName("UTF-8"));

System.out.println(s);

//forcing strings encoded as UTF-8 as an incorrect encoding like

//say ISO-8859-1 causes strange and undefined behavior

String sISO = new String(array, Charset.forName("ISO-8859-1"));

System.out.println(sISO);

将您的字符串打印为UTF-8,然后再打印为ISO-8859-1:

こんにちは

ããã«ã¡ã¯

Eric Leschinski answered 2019-07-26T01:49:22Z

0 votes

这个问题的根源是如何将字节解码为字符串?

这可以使用JAVA NIO CharSet完成:

public final CharBuffer decode(ByteBuffer bb)

07447e78a70c1f880a51a5a22be4483e.png

宏杰李 answered 2019-07-26T01:50:00Z

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值