OS X 的 java 执行路径中的空格
在 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");
想法?
编辑:转义反斜杠...仍然不起作用。
On OS X, I am trying to .exec something, but when a path contains a space, it doesn't work. I've tried surrounding the path with quotes, escaping the space, and even using \u0020.
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Sun 论坛上有一个关于此问题的摘要...似乎这是一个非常常见的问题,不仅限于 OS X。
线程中的最后一篇文章总结了建议的解决方案。 本质上,使用采用
String[]
数组的Runtime.exec
形式:或者(论坛建议这也可以)
There's a summary of this problem on Sun's forums... seems to be a pretty common issue not restricted to OS X.
The last post in the thread summarizes the proposed solution. In essence, use the form of
Runtime.exec
that takes aString[]
array:or (the forum suggests this will work too)
试试这个:
“\”只会在字符串中放置一个空格,但是“\”会在字符串中放置一个“\”,该字符串将被传递到shell,并且shell将转义该空格。
如果这不起作用,请将参数作为数组传递,每个参数一个元素。 这样 shell 就不会介入,你也不需要奇怪的逃逸。
Try this:
"\ " 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.
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.
Paul 的选项有效,但您仍然必须像这样转义空格:
使用 String 数组的糟糕之处在于每个参数及其选项必须位于其自己的元素中。 例如,您不能这样做:
但必须像这样指定它:
Paul's option works, but you still must escape the spaces like so:
The thing that sucks about using a String array is that each param and its option must be in their own element. For instance you cannot do this:
But instead must specify it like so:
在 Kotlin 中,我能够使用模板化字符串转义空格。
In Kotlin, I was able to escape white spaces using templated strings.