【发布时间】:2014-06-01 02:43:09
【问题描述】:
使用 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))
}
【问题讨论】:
标签: java string scala bytearray