Ridzuan Adris
Ridzuan Adris

Reputation: 1272

Cant run commands With PATH with command prompt using Java?

i want to run a program command with window command prompt. i have to specify the path of the program before i can execute my command. i have seen other SO question but most answer only have command without path.

try {

Runtime rt = Runtime.getRuntime();
String str ="C:/Rsync/rsync -v -e ssh /cygdrive/c/test/from.zip zulkifli@address:/home/zulkifli/test/";   //put path and command

//i put path and command to str string but this will return error 
Process process = Runtime.getRuntime().exec(new String[]{"cmd.exe", "/c",str});
rt.exec("cmd.exe /c start command");

System.out.println(str);

} catch (Exception ex) {}

if we do manually from command prompt we can insert path with cd path/.. and then input the command.

but how does we program it with java? below is the error when i execute the program. the command is legal when i run at cmd

enter image description here

Upvotes: 0

Views: 402

Answers (1)

flob
flob

Reputation: 3908

You could build the process with the ProcessBuilder, don't do cd, don't call cmd.exe.

    String commands = "C:/Rsync/rsync -v -e ssh /cygdrive/c/test/from.zip zulkifli@address:/home/zulkifli/backup_data/";
    String[] commandArray = commands.split("\\s+");
    ProcessBuilder processBuilder = new ProcessBuilder(commandArray);
    Process process = processBuilder.start();
    process.waitFor();

Upvotes: 1

Related Questions