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 ?
我的Scala代码从byte stream获得了一个二进制代码,它看起来像[61 62 63 64]。内容是“abcd”。我用toString来转换p,但是失败了。如何打印成字符串?
2 个解决方案
#1
8
You could convert the byte array to a char array, and then construct a string from that
您可以将字节数组转换为char数组,然后从中构造一个字符串
scala> val bytes = Array[Byte]('a','b','c','d')
bytes: Array[Byte] = Array(97, 98, 99, 100)
scala> (bytes.map(_.toChar)).mkString
res10: String = abcd
scala>
#2
19
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.
如果不指定,则使用默认字符集。
#1
8
You could convert the byte array to a char array, and then construct a string from that
您可以将字节数组转换为char数组,然后从中构造一个字符串
scala> val bytes = Array[Byte]('a','b','c','d')
bytes: Array[Byte] = Array(97, 98, 99, 100)
scala> (bytes.map(_.toChar)).mkString
res10: String = abcd
scala>
#2
19
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.
如果不指定,则使用默认字符集。