java 在 Runtime.getRuntime().exec 中有空格和 2 个可执行文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17141767/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 01:06:56  来源:igfitidea点击:

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

javaprocessjava-7runtime.exec

提问by pwatt01

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

我有一个命令,我需要在 java 中沿着这些行运行:

    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

当路径没有空格时,此命令工作正常,但是当我有空格时,我似乎无法让它工作。我尝试了以下操作,运行 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??

但两者似乎都没有做任何事情。关于我做错了什么的任何想法?

回答by MadProgrammer

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

您传递给命令的每个参数都应该是一个单独的 String 元素。

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 argsvariable

每个元素现在将作为一个单独的元素出现在程序args变量中

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

我也非常鼓励你改用ProcessBuilder它,因为它更容易配置并且不需要你在其中包装一些命令"\"...\""