Convert String to ByteArray and then back to original String


I got a String: val s = "Some String". Then I convert it to byte array by: val bytes = s.toByteArray(). I get something like:
[83, 111, 109, 101, 32, 83, 116, 114, 105, 110, 103]
How can I turn this back to the original string? I tried bytes.toString() but got an error:

java.lang.NoSuchMethodError : Method not found: MemberDescription(ownerInternalName = [B, name = toString, desc = ()Ljava/lang/String;, isStatic = false)


See String reference.
Meaning, use String(bytes). Be careful about charsets though. Both conversion to bytes and back use system default encoding. If you get bytes on one system and then convert back to string on another one, you can get garbage.


@darksnake we always use UTF-8 as a default charset for String<->Byte conversions, see


Calling just toString() on a byte array usually doesn’t produce anything useful, but it should not fail either. Could you show the code where you encounter such exception?

You can use bytes.toString(charset) to convert a byte array back to string using the given encoding.


Oh, great! In java it was a source of a lot of problems.