I am a beginner in Java, I have array of bytes that I need to convert to string.
After that I want to change it back from string to array of bytes.
I tried the code below, but it did not work since the return value from line 2 does not match the original array:
byte[] comData = byteArray;
String value = new String(comData);
byte[] comData2 = value.getBytes();
// comData2 does not equal comData
If this is an arbitrary collection of bytes, i.e. it isn’t actually encoded text, then I’d recommend you use base64. There’s a public domain library available which makes it easy (or various other third party libraries).
Sample code:
Your original code assumes that the data represents text encoded in the platform default encoding. You should almost always avoid using the platform default encoding – if you do want to use a text encoding, it’s usually better to specify one, e.g.
(Of course, if you’re decoding the binary data, then you can’t choose the encoding – you need to know which encoding to use.)