使用 ByteBuffer,我可以将字符串转换为字节数组:
val x = ByteBuffer.allocate(10).put("Hello".getBytes()).array()
> Array[Byte] = Array(104, 101, 108, 108, 111, 0, 0, 0, 0, 0)
将字节数组转换为字符串时,我可以使用new String(x)
。
但是,字符串变成了 hello??????
,我需要在将字节数组转换为字符串之前缩减字节数组。我怎样才能做到这一点?
我使用这段代码来减少零,但我想知道是否有更简单的方法。
def byteArrayToString(x: Array[Byte]) = {
val loc = x.indexOf(0)
if (-1 == loc)
new String(x)
else if (0 == loc)
""
else
new String(x.slice(0,loc))
}
最佳答案
假设 0: Byte
是尾随值,则
implicit class RichToString(val x: java.nio.ByteBuffer) extends AnyVal {
def byteArrayToString() = new String( x.array.takeWhile(_ != 0), "UTF-8" )
}
因此
val x = ByteBuffer.allocate(10).put("Hello".getBytes())
x.byteArrayToString
res: String = Hello
关于java - 在 Java/Scala 中将字节数组转换为字符串时修剪字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23976309/