简体   繁体   English

OS X的java执行路径中的空格

[英]Spaces in java execute path for OS X

On OS X, I am trying to .exec something, but when a path contains a space, it doesn't work.在 OS X 上,我正在尝试 .exec 某些东西,但是当路径包含空格时,它不起作用。 I've tried surrounding the path with quotes, escaping the space, and even using \ .我试过用引号包围路径,转义空间,甚至使用\ 。

For example, this works:例如,这有效:

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

But if there's a space, none of these work:但如果有空间,这些都不起作用:

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

Ideas?想法?

Edit: Escaped backslash... still no worky.编辑:转义的反斜杠......仍然没有工作。

There's a summary of this problem on Sun's forums ... seems to be a pretty common issue not restricted to OS X. Sun的论坛上有一个关于这个问题的摘要......似乎是一个非常常见的问题,不仅限于OS X.

The last post in the thread summarizes the proposed solution. 该主题中的最后一篇文章总结了所提出的解决方案。 In essence, use the form of Runtime.exec that takes a String[] array: 实质上,使用带有String[]数组的Runtime.exec形式:

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

or (the forum suggests this will work too) 或(论坛建议这也会起作用)

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

Try this: 试试这个:

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

"\\ " will just put a space in the string, but "\\ " will put a "\\ " in the string, which will be passed to the shell, and the shell will escape the space. “\\”只会在字符串中放置一个空格,但“\\”会在字符串中放入一个“\\”,它将被传递给shell,而shell将转义空格。

If that doesn't work, pass in the arguments as an array, one element for each argument. 如果这不起作用,请将参数作为数组传入,每个参数一个元素。 That way the shell doesn't get involved and you don't need bizarre escapes. 这样shell就不会涉及到你并不需要奇怪的逃脱。

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

Paul's option works, but you still must escape the spaces like so: 保罗的选择有效,但你仍然必须逃离这样的空间:

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

The thing that sucks about using a String array is that each param and its option must be in their own element. 使用String数组很糟糕的是每个param及其选项必须在它们自己的元素中。 For instance you cannot do this: 例如,你不能这样做:

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

But instead must specify it like so: 但是必须像这样指定它:

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

In Kotlin, I was able to escape white spaces using templated strings.在 Kotlin 中,我能够使用模板字符串转义空格。

private const val chromeExec = "/Applications/Google 
Chrome.app/Contents/MacOS/Google Chrome"
Runtime.getRuntime().exec(arrayOf("$browserExec", url))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM