在 Runtime.getRuntime().exec 中有空格和 2 个可执行文件 [英] Having spaces in Runtime.getRuntime().exec with 2 executables

查看:18
本文介绍了在 Runtime.getRuntime().exec 中有空格和 2 个可执行文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个命令需要在 java 中按照以下方式运行:

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

    C:path	hat hasspacesplink -arg1 foo -arg2 bar "path/on/remote/machine/iperf -arg3 hello -arg4 world"

当路径没有空格时,这个命令可以正常工作,但是当我有空格时,我似乎无法让它工作.我尝试了以下操作,运行 Java 1.7

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

以及

String[] a = "C:path	hat 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??

推荐答案

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

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	hat hasspacesplink",
    "-arg1",
    "foo", 
    "-arg2",
    "bar",
    "path/on/remote/machine/iperf -arg3 hello -arg4 world"};

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

Each element will now appear as a individual element in the programs args variable

我也非常鼓励您使用 ProcessBuilder 代替,因为它更容易配置并且不需要您将某些命令包装在 ""...""

这篇关于在 Runtime.getRuntime().exec 中有空格和 2 个可执行文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆