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

1

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

Heist answered 17/6, 2013 at 6:44 Comment(1)
As general advice: Read (and implement) all the recommendations of When Runtime.exec() won't. 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.Honorary
C
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 "\"...\""

Commute answered 17/6, 2013 at 6:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.