简体   繁体   English

将字节数组转换为String Java

[英]Converting byte array to String Java

I wish to convert a byte array to String but as I do so, my String has 00 before every digit got from the array. 我希望将字节数组转换为String,但是这样做时,我的String在从数组中获取每个数字之前都有00。

I should have got the following result: 49443a3c3532333437342e313533373936313835323237382e303e 我应该得到以下结果:49443a3c3532333437342e313533373936313835323237382e303e

But I have the following: 但是我有以下几点:

在此处输入图片说明

Please help me, how can I get the nulls away? 请帮助我,我怎样才能消除零点?

I have tried the following ways to convert: 我尝试了以下方法进行转换:

xxxxId is the byteArray xxxxId是byteArray

String xxxIdString = new String(Hex.encodeHex(xxxxId)); 字符串xxxIdString =新字符串(Hex.encodeHex(xxxxId));

Thank you! 谢谢!

Try something like this: 尝试这样的事情:

String s = new String(bytes);
s = s.replace("\0", "")

It's also posible, that the string will end after the first '\\0' received, if thats the case, first iterate through the array and replace '\\0' with something like '\\n' and do this: 这也是可能的,字符串将在收到第一个“ \\ 0”之后结束,如果是这种情况,请首先遍历数组并将“ \\ 0”替换为“ \\ n”,然后执行以下操作:

String s = new String(bytes);
s = s.replace("\n", "")

EDIT: use this for a BYTE-ARRAY: 编辑:将其用于字节数组:

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

use this for a CHAR: 将此用于CHAR:

String s = new String(bytes);

In order to convert Byte array into String format correctly, we have to explicitly create a String object and assign the Byte array to it. 为了将Byte数组正确地转换为String格式,我们必须显式创建一个String对象并为其分配Byte数组。

 String example = "This is an example";
 byte[] bytes = example.getBytes();
 String s = new String(bytes);

Try below code: 试试下面的代码:

byte[] bytes = {...} 
String str = new String(bytes, "UTF-8"); // for UTF-8 encoding

please have a look here- How to convert byte array to string and vice versa? 请在这里看看- 如何将字节数组转换为字符串,反之亦然?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM