Trimming byte array when converting byte array to string in Java/Scala
- by prosseek
Using ByteBuffer, I can convert a string into byte array:
val x = ByteBuffer.allocate(10).put("Hello".getBytes()).array()
> Array[Byte] = Array(104, 101, 108, 108, 111, 0, 0, 0, 0, 0)
When converting the byte array into string, I can use new String(x).
However, the string becomes hello?????, and I need to trim down the byte array before converting it into string. How can I do that?
I use this code to trim down the zeros, but I wonder if there is simpler way.
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))
}