1

Have Seq[Byte] in scala . How to convert it to java byte[] or Input Stream ?

3 Answers 3

4

wouldn't

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

do the job?

Sign up to request clarification or add additional context in comments.

Comments

0

You can copy the contents of a Seq With copyToArray.

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

Note that this will iterate through the Seq twice, which may be undesirable, impossible, or just fine, depending on your use.

Comments

0

A sensible option:

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

A less sensible option:

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)
  }
}

1 Comment

Sensible Option Worked. Thanks !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.