Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect string to scala.sys.process

Tags:

scala

The documentation for scala.sys.process provides examples on how to redirect a URL or File to a process (stdin). But how can a string be redirected?

I use Scala 2.9.

like image 435
Tobias Furuholm Avatar asked Nov 11 '12 20:11

Tobias Furuholm


2 Answers

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
like image 99
sourcedelica Avatar answered Oct 14 '22 13:10

sourcedelica


Updating @soucredelica's answer, I also show how to concatenate the Stream of String to a String using mkString:

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 inputStream = new ByteArrayInputStream(inputString.getBytes("UTF-8"))
inputStream: java.io.ByteArrayInputStream = java.io.ByteArrayInputStream@28d101f3

scala> val outputStream: Stream[String] = (cmd #< inputStream).lineStream_!
outputStream: Stream[String] = Stream(hello, ?)

scala> println(outputStream.mkString("\n"))
hello
world
like image 39
Mike Slinn Avatar answered Oct 14 '22 14:10

Mike Slinn