scs075 scs075 - 6 months ago 27
Java Question

byte[] to String to byte[] again

Here is what I am trying to do. I have a byte[] that I need to store in Redis with key(say key1) Redis will store it as a String. I need to reconstruct the byte[] upon retrieving the value via the key1

//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)+ "<<");


But I get the following output:


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]<<


What am I doing wrong? Is there any better solution to this?

Answer

Arrays.toString() doesn't transform a byte array into a String. It gives a String representation of a byte array, for debugging purposes, as List<Byte>.toString() would do.

Base64.encode() should transform a byte array into a String. And Base64.decode() should transform a base64 string into the corresponding byte array. All the Base64 libraries I've seen have such a method built-in. Yours probably has one as well. If it doesn't, Base64 containing ASCII characters, you can simply use

String storeStr = new String(base64Array, "ASCII");

and

byte[] bytes = storeStr.getBytes("ASCII");