I wrote a code writing 8 different values of sine in byte form (using .getbytes) into a text file.
After I run it a file is created containing the following: [B@5f18cd5 [B@1c515979 [B@20c92575 [B@75ba3523 [B@f4c7f77 [B@67446579 [B@3b621fe6 [B@271c537f
So far so good...
I'd now like to inverse this whole process in another Java project. For this I need to know how to turn for example [B@1c515979 back to it's initial value which is 0.7071.
I tried to use
System.out.println("Text [Byte Format] : " + bytes.toString());
with which I hoped to convert the byte code back to string. The problem though, is that since I'm reading from a text file I guess the read data is string anyway, so actually I'm just turning strings into strings.
This is my status quo... Anyone got an idea?
Thanks for listening.
You can't. You've already lost all the important data. Calling toString()
on a byte[]
doesn't give you anything useful, because arrays in Java don't override toString()
... so you're getting the implementation from Object
, which just indicates the type and the hash code (which is effectively the identity hash code, for arrays). If you modify the content of the byte array and call toString()
on it, you'll get the same value.
Instead, you need to change how you're saving the data. If you can avoid needing a text file at all, that would be ideal... but if you do need a text file, the simplest option is probably to convert the binary data to base64, e.g. using java.util.Base64
:
String text = Base64.getEncoder().encodeToString(bytes);
// Write out text...
...
// String text = // read from a file
byte[] bytes = Base64.getDecoder().decode(text);
See more on this question at Stackoverflow