13

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??

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
pwatt01
  • 155
  • 1
  • 1
  • 9
  • As general advice: Read (and implement) *all* the recommendations of [When Runtime.exec() won't](http://www.javaworld.com/jw-12-2000/jw-1229-traps.html). That might solve the problem. If not, it should provide more information as to the reason it failed. Then ignore that it refers to `exec` and build the `Process` using a `ProcessBuilder`. Also break a `String arg` into `String[] args` to account for arguments which themselves contain spaces. – Andrew Thompson Jun 17 '13 at 07:04

1 Answers1

21

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 "\"...\""

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366