【问题标题】:Spaces in java execute path for OS XOS X的java执行路径中的空格
【发布时间】:2010-10-16 09:44:35
【问题描述】:

在 OS X 上,我正在尝试 .exec 某些东西,但是当路径包含空格时,它不起作用。我试过用引号包围路径,转义空间,甚至使用 \u0020。

例如,这是有效的:

Runtime.getRuntime().exec("open /foldername/toast.sh");

但如果有空格,这些都不起作用:

Runtime.getRuntime().exec("open /folder name/toast.sh");

Runtime.getRuntime().exec("open \"/folder name/toast.sh\"");

Runtime.getRuntime().exec("open /folder\\ name/toast.sh");

Runtime.getRuntime().exec("open /folder\u0020name/toast.sh");

想法?

编辑:转义的反斜杠......仍然没有工作。

【问题讨论】:

    标签: java runtime escaping space


    【解决方案1】:

    试试这个:

    Runtime.getRuntime().exec("open /folder\\ name/toast.sh");
    

    “\”只会在字符串中放一个空格,而“\”会在字符串中放一个“\”,它会传递给shell,shell会将空格转义。

    如果这不起作用,请将参数作为数组传递,每个参数一个元素。这样,shell 就不会参与其中,您也不需要奇怪的转义。

    Runtime.getRuntime().exec(new String[]{"open", "/folder name/toast.sh"});
    

    【讨论】:

    • 哎呀,那是我的错字,我试过了,这不起作用。
    【解决方案2】:

    Sun's forums 上有一个关于这个问题的总结……这似乎是一个很常见的问题,不仅限于 OS X。

    线程中的最后一篇文章总结了建议的解决方案。本质上,使用Runtime.exec 的形式,它采用String[] 数组:

    String[] args = new String[] { "open", "\"/folder name/toast.sh\"" }; 
    

    或者(论坛建议这也可以)

    String[] args = new String[] { "open", "folder name/toast.sh" };
    

    【讨论】:

    • 谢谢!仅供参考,我在实际程序中有一些额外的标志,如果你使用这样的数组,那么你必须分解所有内容。示例:String[] args = new String[] { "open", "-n", "文件夹名/toast.sh" };
    • 现在是死链接 :( 有人知道我在哪里可以找到替换链接吗?
    【解决方案3】:

    Paul 的选项有效,但您仍然必须像这样转义空格:

    Runtime.getRuntime().exec(new String[]{"open", "/folder\\ name/toast.sh"});
    

    使用字符串数组的糟糕之处在于每个参数及其选项必须在它们自己的元素中。例如,您不能这样做:

    Runtime.getRuntime().exec(new String[]{"executable", "-r -x 1", "/folder\\ name/somefile"});
    

    但必须像这样指定它:

    Runtime.getRuntime().exec(new String[]{"executable", "-r", "-x", "1", "/folder\\ name/somefile"});
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-09
      • 2011-08-16
      • 2016-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多