Search code examples
javacommandapache-commons-exec

Java - apache commons exec, run 2 commands in same "context"


I am unsure if context is the right word to use here but what i mean is something like

cd .\test
test.exe

test.exe is located in the folder test and I want to run it from the folder test, I know I can run

.\test\test.exe

but I need test.exe to be run from the folder test.

Is there a way to run both commands in the same "context"?

I have tried:

String cmd1 = "cmd /C cd test";
String cmd2 = "test.exe";
CommandLine cmdl1 = CommandLine.parse(cmd1);
CommandLine cmdl2 = CommandLine.parse(cmd2);
DefaultExecutor exec = new DefaultExecutor();
exec.execute(cmdl1);
exec.execute(cmdl2);

but as expected it could not find test.exe.


Solution

  • I would try executing both commands joined together using the && operator.

    Like:

    cd .\test && .\test.exe
    

    This will first change directories, and if successful, execute the test.exe executable in that directory. If the change directory is not successful, the second half of the command will not execute.