Redirect string to scala.sys.process
Besides a File
or URL
you can also provide an InputStream
to ProcessBuilder
.
There are a variety of ways to convert a String
into an InputStream
. In the below I am using ByteArrayInputStream
and String.getBytes
.
As an example I will run good old cat
with the input set to the contents of inputString
.
scala> import java.io.ByteArrayInputStream
import java.io.ByteArrayInputStream
scala> import scala.sys.process._
import scala.sys.process._
scala> val cmd = List("cat")
cmd: List[java.lang.String] = List(cat)
scala> val inputString = "hello\nworld"
inputString: java.lang.String =
hello
world
scala> val is = new ByteArrayInputStream(inputString.getBytes("UTF-8"))
is: java.io.ByteArrayInputStream = java.io.ByteArrayInputStream@28d101f3
scala> val out = (cmd #< is).lines_!
out: Stream[String] = Stream(hello, ?)
scala> out.foreach(println)
hello
world