Search code examples
javacommand-promptprocessbuilder

How to Run two different commands using process builder


Sorry if I am Re-opening the same Question again. I want to Run Two Commands

  1. D:\cygwin\bin\Test

  2. sh app.sh AK-RD 02.20 D:\cygwin\bin\Test_files

Above are the two commands i want to run in the same command prompt Means i have to go inside D:\cygwin\bin\Test Folder and on the same prompt want to run next command

sh app.sh AK-RD 02.20 D:\cygwin\bin\Test_files

The command will look like,

Command:- D:\cygwin\bin\Test>sh app.sh AK-RD 02.20 D:\cygwin\bin\Test_files

How to do this using process Builder in java. Or is there any other way to do this.

String cmd;   
   cmd = "sh app.sh AK-RD 02.20 D:\\cygwin\\bin\\Test_files";
    ProcessBuilder probuilder = new ProcessBuilder( cmd );
    probuilder.directory(new File("D:\\cygwin\\bin\\Test"));
    Process process = probuilder.start();

This is not Helping me, Even if i change probuilder.directory in the code. I am getting

Cannot run program "'sh app.sh AK-RD 02.20 D:\\cygwin\\bin\\Test_files  CreateProcess error=2, The system cannot find the file specified

Solution

  • The error means the system can't find the file sh app.sh AK-RD 02.20 D:\\cygwin\\bin\\Test_files.exe in the path.

    This means that ProcessBuilder interprets the whole string (including backslashes and spaces and everything) as command name. This is not what you want.

    Split the command into individual words:

    ProcessBuilder pb = new ProcessBuilder( "sh", "app.sh", "AK-RD", "02.20", "D:\\cygwin\\bin\\Test_files" );
    

    and use pb.directory() to CD into the correct directory.

    Alternatively, put everything into a BAT/CMD script and run that with ProcessBuilder