string 将字节数组转换为字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45233355/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
convert a byte array to string
提问by Robin
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 代码从字节流中接收到一个二进制文件,它看起来像 [61 62 63 64]。内容是“abcd”。我使用 toString 将其转换为 p,但失败了。如何将其打印为字符串?
采纳答案by cms
You could convert the byte array to a char array, and then construct a string from that
您可以将字节数组转换为字符数组,然后从中构造一个字符串
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>
回答by Sleiman Jneidi
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.
Charset
如果您不指定任何内容,则将使用默认值。