byte []再次转换为字符串[]

scs*_*075 1 java bytearray

这是我想要做的.我有一个byte [],我需要用密钥存储在Redis中(比如key1)Redis会将它存储为String.我需要在通过key1检索值时重建byte []

    //here is a byte array
    byte[] bArr = new byte[] {83, 71, 86, 115, 98, 71, 56, 103, 84, 88, 73, 117, 73, 69, 104, 118, 100, 121, 66, 107, 98, 121, 66, 53, 98, 51, 85, 103, 90, 71, 56, 47}; //"Hello World"; 

    // I will have to store this as a byte string into redis
    //Base64 encoding
    bArr = Base64.encodeBase64(bArr);
    String storeStr = Arrays.toString(bArr) ;
    // storeStr is what gets stored in redis
    System.out.println("storeStr>>" + storeStr+ "<<");
    // I will get this string back from redis
    // now trying to reconstruct the byte[]
    byte[] aArr = Base64.decodeBase64(storeStr); 
    System.out.println("readStr>>" + Arrays.toString(aArr)+ "<<");  
Run Code Online (Sandbox Code Playgroud)

但我得到以下输出:

storeStr >> [85,48,100,87,99,50,74,72,79,71,100,85,87,69,108,49,83,85,86,111,100,109,82, 53,81,109,116,105,101,85,73,49,89,106,78,86,90,49,112,72,79,67,56,61] << readStr >> [ - 13 ,-98,60,-41,77,60,-17,-33,121,-45,-66,59,-37,-65,123,-41,93,52,-13,-97, 59,-21,-35,116,-13,-113,124,-33,-50,124,-21,93,117,-41,77,53,-45,-33,54,-25 ,127,53,-41,79,117,-41,-83,116,-25,93,53,-13,-98,-9,-29,-33,61,-41,78, - 69,-13,-50,-67,-45,-113,117,-41,110,-10,-17,-34,-69,-25,-82,-75] <<

我究竟做错了什么?有没有更好的解决方案呢?

JB *_*zet 6

Arrays.toString()不会将字节数组转换为String.它给出了一个字节数组的字符串表示,用于调试目的,就像List<Byte>.toString()这样做.

Base64.encode()应该将字节数组转换为String.并且Base64.decode()应该将base64字符串转换为相应的字节数组.我见过的所有Base64库都内置了这样的方法.你的可能也有一个.如果没有,Base64包含ASCII字符,你可以简单地使用

String storeStr = new String(base64Array, "ASCII");
Run Code Online (Sandbox Code Playgroud)

byte[] bytes = storeStr.getBytes("ASCII");
Run Code Online (Sandbox Code Playgroud)