Search code examples
shellscalawindows-7cross-platformdos

Using scala.sys.process to invoke echo on Windows 7


I am trying to use an external program from within Scala that accepts its input from the standard input stream.

Code roughly the equivalent to the following runs on Linux but raises an exception when run on Windows (tested on Windows 7). The exception's description states that the echo command cannot be found.

def invokeProgram(data : String) {
       import scala.sys.process._
       val cmdEcho = Seq("echo", data)
       val cmdProgram = Seq("program")
       println((cmdEcho #| cmdProgram).!!)
}

The code works correctly on Linux but fails as described on Windows, yet the echo command is common to both platforms and its usage is syntactically the same for my purposes. Is this as simple as echo not being in PATH? Is there even a separate echo.exe on Windows or is it bundled into something else? The invoked program can be made to accept its input from a temporary file which is what I will fall back to if I cannot resolve this issue.


Solution

  • You don't need to use echo at all. Instead, use the #< method of ProcessBuilder. Here is an example:

    import java.io.ByteArrayInputStream
    import scala.sys.process._
    
    val data = "hello"
    val is = new ByteArrayInputStream(data.getBytes)
    "cat" #< is ! //complicated way to print hello