convert a byte array to string

Robin picture Robin · Jul 21, 2017 · Viewed 45.4k times · Source

My Scala code received a binary from byte stream,it looks like [61 62 63 64].The content is "abcd". I use toString to convert it p, but failed. How do I print it as string ?

Answer

Sleiman Jneidi picture Sleiman Jneidi · Jul 21, 2017

You can always convert the byte array to a string if you know its charset,

val str = new String(bytes, StandardCharsets.UTF_8)

And the default Charset would used if you don't specify any.