Search code examples
scalaprocessbuilder

Passing process stdout to outside function


I'm trying to implement a function that starts a process and returns its stdout as InputStream.

def getStuff(): InputStream = ???

Seems pretty easy to do in Java but I can't figure out how to do it using sys.process in Scala.


Solution

  • You can pipe the output of a command to OutputSteam with #>. Then you just need to copy OutputStream to InputStream:

    import scala.sys.process._
    import java.io._
    import scala.io.Source
    
    def getStuff(): InputStream = {
      val os   =  new ByteArrayOutputStream
      ("echo 'Hello'" #> os).!
      new ByteArrayInputStream(os.toByteArray());
    }
    
    Source.fromInputStream(getStuff()).mkString //"Hello"