将Scala中的Seq [Byte]转换为byte [] / InputStream

时间:2015-04-08 09:00:10

标签: java scala

在scala中有Seq [Byte]。如何将其转换为java byte []或Input Stream?

3 个答案:

答案 0 :(得分:4)

不会

val a: Seq[Byte] = List()
a.toArray

做这个工作?

答案 1 :(得分:0)

您可以使用Seq复制copyToArray的内容。

val myseq: Seq[Byte] = ???
val myarray = new Array[Byte](myseq.size)
myseq.copyToArray(myarray)

请注意,这将在Seq中重复两次,这可能是不可取的,不可能的,或者很好,具体取决于您的用途。

答案 2 :(得分:0)

明智的选择:

val byteSeq: Seq[Byte] = ???
val byteArray: Array[Byte] = bSeq.toArray
val inputStream = java.io.ByteArrayInputStream(byteArray)

一个不太明智的选择:

object HelloWorld {

  implicit class ByteSequenceInputStream(val byteSeq: Seq[Byte]) extends java.io.InputStream {
    private var pos = 0
    val size = byteSeq.size
    override def read(): Int = pos match {
        case `size` => -1 // backticks match against the value in the variable
        case _ => {
          val result = byteSeq(pos).toInt
          pos = pos + 1
          result
        }
      }
  }

  val testByteSeq: Seq[Byte] = List(1, 2, 3, 4, 5).map(_.toByte)
  def testConversion(in: java.io.InputStream): Unit = {
    var done = false
    while (! done) {
      val result = in.read()
      println(result)
      done = result == -1
    }
  }

  def main(args: Array[String]): Unit = {
    testConversion(testByteSeq)
  }
}