Search code examples
scalaprocessprocessbuilder

Run a process on Scala with a different working directory and input redirect


It seems like it is impossible to run a process on Scala with another working directory and input redirect.

This is how I would typically run a process on Scala with a default directory:

Process(cmd, new File("someDir")).!!

And this is how I would typically run a process on Scala with input redirect:

("someCmd -someParam" #< "myFile.txt").!!

It seems like it is impossible to combine the two..

Am I missing anythign?


Solution

  • #< is a method on ProcessBuilder, so you can just call:

    (Process("someCmd -someParam", new File("someDir")) #< new File("myFile.txt")).!!
    

    Note, that the File you pass as input has to be specified relative to the working directory of the Scala process. But if instead you are passing the file path as an argument to the command, the path has to be relative to the working directory of the command.

    So, for myFile.txt inside someDir, the calls may look like this:

    (Process("someCmd -someParam", new File("someDir")) #< new File("someDir/myFile.txt")).!!
    

    But,

    Process("cat myFile.txt", new File("someDir")).!!