Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 985
Glenn Avatar asked Mar 30 '09 15:03

Glenn


People also ask

How do I type a space in Terminal Mac?

Either escape the space with a backslash or use quotes. You can also use autocomplete with tab.


2 Answers

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 a String[] array:

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" };
like image 122
Jarret Hardie Avatar answered Sep 23 '22 18:09

Jarret Hardie


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.

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.

Runtime.getRuntime().exec(new String[]{"open", "/folder name/toast.sh"});
like image 26
Paul Tomblin Avatar answered Sep 20 '22 18:09

Paul Tomblin