问题
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??
回答1:
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 "\"...\""
来源:https://stackoverflow.com/questions/17141767/having-spaces-in-runtime-getruntime-exec-with-2-executables