Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Having spaces in Runtime.getRuntime().exec with 2 executables

I have a command that I need to run in java along these lines:

    C:\path\that has\spaces\plink -arg1 foo -arg2 bar "path/on/remote/machine/iperf -arg3 hello -arg4 world"

This command works fine when the path has no spaces, but when I have the spaces I cannot seems to get it to work. I have tried the following things, running Java 1.7

String[] a = "C:\path\that has\spaces\plink", "-arg1 foo", "-arg2 bar", "path/on/remote/machine/iperf -arg3 hello -arg4 world"
Runtime.getRuntime().exec(a);

as well as

String[] a = "C:\path\that has\spaces\plink", "-arg1 foo", "-arg2 bar", "path/on/remote/machine/iperf", "-arg3 hello", "-arg4 world"
Runtime.getRuntime().exec(a);

But neither seem to be doing anything. Any thoughts on what i am doing wrong??

like image 301
pwatt01 Avatar asked Jun 17 '13 06:06

pwatt01


1 Answers

Each argument you pass to the command should be a separate String element.

So you command array should look more like...

String[] a = new String[] {
    "C:\path\that has\spaces\plink",
    "-arg1",
    "foo", 
    "-arg2",
    "bar",
    "path/on/remote/machine/iperf -arg3 hello -arg4 world"};

Each element will now appear as a individual element in the programs args variable

I would also, greatly, encourage you to use ProcessBuilder instead, as it is easier to configure and doesn't require you to wrap some commands in "\"...\""

like image 135
MadProgrammer Avatar answered Sep 22 '22 14:09

MadProgrammer