Java字节数组到字符串到字节数组

新手上路,请多包涵

我试图理解字节 [] 到字符串,字节 [] 到字节 [] 转换的字符串表示…我将我的字节 [] 转换为要发送的字符串,然后我期望我的 Web 服务(用 python 编写)将数据直接回显给客户端。

当我从我的 Java 应用程序发送数据时…

 Arrays.toString(data.toByteArray())

要发送的字节..

 [B@405217f8

发送(这是 Arrays.toString() 的结果,它应该是我的字节数据的字符串表示,该数据将通过网络发送):

 [-47, 1, 16, 84, 2, 101, 110, 83, 111, 109, 101, 32, 78, 70, 67, 32, 68, 97, 116, 97]

在python端,python服务器返回一个字符串给调用者(我可以看到和我发送给服务器的字符串一样

[-47, 1, 16, 84, 2, 101, 110, 83, 111, 109, 101, 32, 78, 70, 67, 32, 68, 97, 116, 97]

服务器应将此数据返回给客户端,以便在客户端进行验证。

我的客户收到的响应(作为字符串)看起来像

[-47, 1, 16, 84, 2, 101, 110, 83, 111, 109, 101, 32, 78, 70, 67, 32, 68, 97, 116, 97]

我似乎无法弄清楚如何将接收到的字符串恢复为 byte[]

无论我尝试什么,我最终都会得到一个字节数组,如下所示……

 [91, 45, 52, 55, 44, 32, 49, 44, 32, 49, 54, 44, 32, 56, 52, 44, 32, 50, 44, 32, 49, 48, 49, 44, 32, 49, 49, 48, 44, 32, 56, 51, 44, 32, 49, 49, 49, 44, 32, 49, 48, 57, 44, 32, 49, 48, 49, 44, 32, 51, 50, 44, 32, 55, 56, 44, 32, 55, 48, 44, 32, 54, 55, 44, 32, 51, 50, 44, 32, 54, 56, 44, 32, 57, 55, 44, 32, 49, 49, 54, 44, 32, 57, 55, 93]

或者我可以获得如下字节表示形式:

 B@2a80d889

这两个都与我发送的数据不同……我确定我错过了一些非常简单的东西……

有什么帮助吗?!

原文由 0909EM 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 481
2 个回答

您不能只获取返回的字符串并从中构造一个字符串……它不再是 byte[] 数据类型,它已经是一个字符串;你需要解析它。例如 :

 String response = "[-47, 1, 16, 84, 2, 101, 110, 83, 111, 109, 101, 32, 78, 70, 67, 32, 68, 97, 116, 97]";      // response from the Python script

String[] byteValues = response.substring(1, response.length() - 1).split(",");
byte[] bytes = new byte[byteValues.length];

for (int i=0, len=bytes.length; i<len; i++) {
   bytes[i] = Byte.parseByte(byteValues[i].trim());
}

String str = new String(bytes);

** 编辑**

You get an hint of your problem in your question, where you say ” Whatever I seem to try I end up getting a byte array which looks as follows... [91, 45, ... “, because 91 is the byte value for [ , so [91, 45, ... 是字符串“ [-45, 1, 16, ... ”字符串的字节数组。

方法 Arrays.toString() 将返回指定数组的 String 表示;这意味着返回值将不再是数组。例如 :

 byte[] b1 = new byte[] {97, 98, 99};

String s1 = Arrays.toString(b1);
String s2 = new String(b1);

System.out.println(s1);        // -> "[97, 98, 99]"
System.out.println(s2);        // -> "abc";

As you can see, s1 holds the string representation of the array b1 , while s2 holds the string representation of the bytes contained in b1

现在,在您的问题中,您的服务器返回类似于 s1 的字符串,因此要取回数组表示形式,您需要相反的构造函数方法。如果 s2.getBytes()new String(b1) 的对立面,你需要找到 Arrays.toString(b1) 的对立面,因此我粘贴了这个答案的第一个代码片段。

原文由 Yanick Rochon 发布,翻译遵循 CC BY-SA 3.0 许可协议

String coolString = "cool string";

byte[] byteArray = coolString.getBytes();

String reconstitutedString = new String(byteArray);

System.out.println(reconstitutedString);

这会将“cool string”输出到控制台。

这非常容易。

原文由 CorayThan 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题