2

I have a String variable say string that I converted into byte[] and then I encoded the same using Base64 in as byte[] say encodedByteArr. Using the below code:

String string = "Test";
byte[] encodedByteArr= null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(check);
encodedByteArr= Base64.encodeBase64(bos.toByteArray());
oos.flush();
oos.close();
bos.close();
System.out.println("Encoded value is:- "+encodedByteArr);

Output is:

Encoded value is:- [B@5fd0d5ae

Now, I receive the same encoded value in another method as a String, which means:

String string = "[B@5fd0d5ae";

And it is nothing but a String representation of byte[] which I generated in above code.

Now my task is to actually decode the value and get back the original text back, that is "Test".

And for that, I want the String representation of byte[] back to a an byte[] without losing its integrity.

  • See https://stackoverflow.com/questions/409784/whats-the-simplest-way-to-print-a-java-array – Stephen C Oct 15 '17 at 22:22
  • You have actually solved your problem already (I think). The problem is that you are printing the array the wrong way ... and the output makes you *think* you have done it incorrectly. – Stephen C Oct 15 '17 at 22:25
  • You'll never decode anything out of `[B@5fd0d5ae`. You'll need a more meaningful encoding than the default `toString()`. – shmosel Oct 16 '17 at 00:25

3 Answers3

0

All Java arrays print like that. It's the way they work. If you want to print the contents of the array, you have to use a static method from java.util.Arrays.

System.out.println("Encoded value is:- "+Arrays.toString(encodedByteArr));

It's kind of dumb, but that's the way it works.

markspace
  • 10,621
  • 3
  • 25
  • 39
0

Now my task is to actually decode the value and get back the original text back

It sounds like you have a Base64-encoded string that you want to decode to yield the original string?

In Java 8, you can do

import java.util.Base64;
byte[] decoded = Base64.getDecoder().decode(string);
String original = new String(decoded);

A full "round trip" would look like:

String original = "Hello";
byte[] encodedBytes = Base64.getEncoder().encode(original.getBytes());
String encodedString = new String(encodedBytes);
System.out.println(encodedString);  // "SGVsbG8="

byte[] decodedBytes = Base64.getDecoder().decode(encodedString);
String decodedString = new String(decodedBytes);
System.out.println(decodedString);  // "Hello"
Myk Willis
  • 12,306
  • 4
  • 45
  • 62
0
System.out.println("decoded raw byte: ");
for (byte singleByte:encodedByteArr) {
    System.out.print((char)singleByte);
}

Will return the string representation of byte to the output.
(not so efficient)