在Java/Scala中将字节数组转换为字符串时修剪字节数组

pro*_*eek 4 java string scala bytearray

使用ByteBuffer,我可以将字符串转换为字节数组:

val x = ByteBuffer.allocate(10).put("Hello".getBytes()).array()
> Array[Byte] = Array(104, 101, 108, 108, 111, 0, 0, 0, 0, 0)
Run Code Online (Sandbox Code Playgroud)

将字节数组转换为字符串时,我可以使用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))
}
Run Code Online (Sandbox Code Playgroud)

elm*_*elm 6

假设那0: Byte是一个尾随值,那么

implicit class RichToString(val x: java.nio.ByteBuffer) extends AnyVal {
  def byteArrayToString() = new String( x.array.takeWhile(_ != 0), "UTF-8" )
}
Run Code Online (Sandbox Code Playgroud)

因此

val x = ByteBuffer.allocate(10).put("Hello".getBytes())

x.byteArrayToString
res: String = Hello
Run Code Online (Sandbox Code Playgroud)