将字节数组转换为String Java [英] Converting byte array to String Java
问题描述
我希望将字节数组转换为String,但是这样做的时候,我的String在从数组中获取每个数字之前都有00。
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.
我应该拥有以下结果:49443a3c3532333437342e313533373936313835323237382e303e
I should have got the following result: 49443a3c3532333437342e313533373936313835323237382e303e
但是我有以下内容:
请帮助我,我如何才能消除空值?
Please help me, how can I get the nulls away?
我尝试了以下方法转换:
I have tried the following ways to convert:
xxxxId是byteArray
xxxxId is the byteArray
String xxxIdString = new String(Hex.encodeHex(xxxxId)) ;
String xxxIdString = new String(Hex.encodeHex(xxxxId));
谢谢!
推荐答案
尝试如下操作:
String s = new String(bytes);
s = s.replace("\0", "")
这也是可能的,则字符串将在收到第一个 \0之后结束,如果是这种情况,请首先遍历数组并将 \0替换为 \n,然后执行以下操作:
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:
String s = new String(bytes);
s = s.replace("\n", "")
编辑:
将其用于字节数组:
use this for a BYTE-ARRAY:
String s = new String(bytes, StandardCharsets.UTF_8);
将此用于CHAR:
String s = new String(bytes);
这篇关于将字节数组转换为String Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!