首页 文章

Java Byte Array to String to Byte Array

提问于
浏览
167

我正在尝试理解byte []到字符串,字节[]到byte []转换的字符串表示...我将我的byte []转换为要发送的字符串,然后我希望我的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]

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

无论我似乎尝试什么,我最终得到一个字节数组,看起来如下......

[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

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

有什么帮助?!

11 回答

  • 7

    如果要将字符串转换回字节数组,则需要使用 String.getBytes() (或等效的Python函数),这样可以打印出原始字节数组 .

  • 1

    [JDK8]

    import java.util.Base64;
    

    要字符串:

    String str = Base64.getEncoder().encode(new byte[]{ -47, 1, 16, ... });
    

    字节数组:

    byte[] bytes = Base64.getDecoder().decode("JVBERi0xLjQKMyAwIG9iago8P...");
    
  • 0

    使用下面的代码API将字节码作为字符串转换为字节数组 .

    byte[] byteArray = DatatypeConverter.parseBase64Binary("JVBERi0xLjQKMyAwIG9iago8P...");
    
  • 251

    [JAVA 8]

    import java.util.Base64;
    
    String dummy= "dummy string";
    byte[] byteArray = dummy.getBytes();
    
    byte[] salt = new byte[]{ -47, 1, 16, ... }
    String encoded = Base64.getEncoder().encodeToString(salt);
    
  • 3

    你可以't just take the returned string and construct a string from it... it'不再是 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);
    

    ** EDIT **

    你在问题中得到了一个问题的提示,你说“ Whatever I seem to try I end up getting a byte array which looks as follows... [91, 45, ... ”,因为 91[ 的字节值,所以 [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";
    

    如您所见, s1 保存 array b1 的字符串表示形式,而 s2 保存 b1 中包含的 bytes 的字符串表示形式 .

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

  • 124
    String coolString = "cool string";
    
    byte[] byteArray = coolString.getBytes();
    
    String reconstitutedString = new String(byteArray);
    
    System.out.println(reconstitutedString);
    

    这将“酷字符串”输出到控制台 .

    这很简单 .

  • 2

    我做了什么:

    return to clients:

    byte[] result = ****encrypted data****;
    
    String str = Base64.encodeBase64String(result);
    
    return str;
    

    receive from clients:

    byte[] bytes = Base64.decodeBase64(str);
    

    您的数据将以以下格式传输:

    OpfyN9paAouZ2Pw+gDgGsDWzjIphmaZbUyFx5oRIN1kkQ1tDbgoi84dRfklf1OZVdpAV7TonlTDHBOr93EXIEBoY1vuQnKXaG+CJyIfrCWbEENJ0gOVBr9W3OlFcGsZW5Cf9uirSmx/JLLxTrejZzbgq3lpToYc3vkyPy5Y/oFWYljy/3OcC/S458uZFOc/FfDqWGtT9pTUdxLDOwQ6EMe0oJBlMXm8J2tGnRja4F/aVHfQddha2nUMi6zlvAm8i9KnsWmQG//ok25EHDbrFBP2Ia/6Bx/SGS4skk/0couKwcPVXtTq8qpNh/aYK1mclg7TBKHfF+DHppwd30VULpA==
    
  • 20

    Arrays.toString() 的作用是在byteArray中创建每个字节的字符串表示 .

    请查看API文档Arrays API

    要将响应字符串转换回原始字节数组,必须使用 split(",") 或其他内容并将其转换为集合,然后将其中的每个项目转换为字节以重新创建字节数组 .

  • 0

    它简单地将字节数组转换为字符串,并将字符串转换回java中的字节数组 . 我们需要知道何时以正确的方式使用“新” . 它可以如下完成:

    字节数组转换为字符串:

    byte[] bytes = initializeByteArray();
    String str = new String(bytes);
    

    字符串到字节数组转换:

    String str = "Hello"
    byte[] bytes = str.getBytes();
    

    有关更多详细信息,请查看:http://evverythingatonce.blogspot.in/2014/01/tech-talkbyte-array-and-string.html

  • 5

    您从字节数组( [B@405217f8 )看到的输出类型也是零长度字节数组(即 new byte[0] )的输出 . 看起来这个字符串是对数组的引用,而不是像我们对常规集合的 toString() 方法所期望的数组内容的描述 .

    与其他受访者一样,我会指向接受 byte[] 参数的 String 构造函数,以根据字节数组的内容构造字符串 . 如果要从TCP连接获取字节,您应该能够从套接字的 InputStream 读取原始字节 .

    如果您已经将这些字节读取为 String (使用 InputStreamReader ),则可以使用 getBytes() 函数将字符串转换为字节 . 确保将所需的字符集传递给String构造函数和 getBytes() 函数,这只有在字节数据可以通过 InputStreamReader 转换为字符时才有效 .

    如果你想处理原始字节,你应该真的避免使用这个流阅读器层 .

  • 1

    你能不能将字节作为字节发送,或者将每个字节转换为字符并作为字符串发送?当你只有11个字节要发送时,像你这样做将在字符串中占用至少85个字符 . 您可以创建字节的字符串表示,因此它可以很容易地"[B@405217f8"在Python中转换为 bytesbytearray 对象 . 如果失败了,您可以将它们表示为一系列十六进制数字("5b42403430353231376638"),占用22个字符,可以使用binascii.unhexlify()在Python端轻松解码 .

相关问题