Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
627 views
in Technique[技术] by (71.8m points)

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

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

    C:pathhat hasspacesplink -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:pathhat hasspacesplink", "-arg1 foo", "-arg2 bar", "path/on/remote/machine/iperf -arg3 hello -arg4 world"
Runtime.getRuntime().exec(a);

as well as

String[] a = "C:pathhat hasspacesplink", "-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??

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:pathhat hasspacesplink",
    "-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 ""...""


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.6k users

...