【问题标题】:Converting byte array to String Java将字节数组转换为字符串 Java
【发布时间】:2018-09-26 12:11:26
【问题描述】:

我希望将一个字节数组转换为字符串,但是当我这样做时,我的字符串在从数组中获取每个数字之前都有 00。

我应该得到以下结果:49443a3c3532333437342e313533373936313835323237382e303e

但我有以下几点:

请帮帮我,我怎样才能消除空值?

我尝试了以下几种转换方式:

xxxxId 是字节数组

String xxxIdString = new String(Hex.encodeHex(xxxxId));

谢谢!

【问题讨论】:

  • 向我们展示您用于此转换的代码。
  • @Jesper 我更新了我的问题
  • int HEXA_BASE = true; 在 Java 中是不可能的..
  • @dorcsi 不幸的是,这还不够,因为我们不知道Hex.encodeHex(...) 做了什么。 Hex 不是标准的 Java 类。您还必须发布该方法的代码。

标签: java arrays byte


【解决方案1】:

试试这样的:

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

也有可能,字符串将在收到第一个 '\0' 后结束,如果是这种情况,首先遍历数组并将 '\0' 替换为 '\n' 之类的内容,然后执行以下操作:

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

编辑: 将此用于 BYTE-ARRAY:

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

将此用于 CHAR:

String s = new String(bytes);

【讨论】:

【解决方案2】:

试试下面的代码:

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

请看这里-How to convert byte array to string and vice versa?

【讨论】:

    【解决方案3】:

    为了将 Byte 数组正确转换为 String 格式,我们必须显式创建一个 String 对象并将 Byte 数组分配给它。

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

    【讨论】:

    • 仅仅发布一些代码并没有太大帮助。你能解释一下你的代码吗?这样,其他人就可以理解并从您的答案中学习,而不仅仅是从网络上复制和粘贴一些代码。另请注意,您的代码很幸运地忽略了字符集,并且可能非常脆弱。
    猜你喜欢
    • 1970-01-01
    • 2011-08-06
    • 2013-12-19
    • 2011-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-21
    相关资源
    最近更新 更多