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

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

问题描述

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

  C:\ path \ thathat has\spaces\plink -arg1 foo -arg2 barpath / on / remote / machine / iperf -arg3 hello -arg4 world

当路径没有空格时,此命令正常工作,但是当我有空格时,我似乎无法使其工作。我尝试过以下操作,运行Java 1.7

  String [] a =C:\ path \ thathathat \\ spaces\plink, -  arg1 foo, -  arg2 bar,path / on / remote / machine / iperf -arg3 hello -arg4 world
Runtime.getRuntime()。exec(a) ;

以及

  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);

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

解决方案

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

所以你的命令数组看起来应该更像...

  String [] a = new String [] {
C:\ path \that has\spaces\plink,
-arg1,
foo,
-arg2,
bar,
path / on / remote / machine / iperf -arg3 hello -arg4 world};

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



我也非常鼓励你使用 ProcessBuilder ,因为它更容易配置,不需要你包含一些命令\... \


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

解决方案

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 "\"...\""

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

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