Spaces in java execute path for OS X
Asked Answered
G

4

9

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.

Gerdagerdeen answered 30/3, 2009 at 15:8 Comment(0)
A
13

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" };
Angelenaangeleno answered 30/3, 2009 at 15:22 Comment(2)
Thanks! FYI I had a few extra flags in the real program and if you use an array like this, you then have to break up everything. Example: String[] args = new String[] { "open", "-n", "folder name/toast.sh" };Gerdagerdeen
Dead link now :( anyone know where I can find a replacement link?Emersed
P
1

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"});
Philippic answered 30/3, 2009 at 15:13 Comment(1)
oops, that was a typo on my part, I have tried and this doesn't work.Gerdagerdeen
P
0

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. 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"});
Pashto answered 7/12, 2009 at 20:18 Comment(0)
L
0

In Kotlin, I was able to escape white spaces using templated strings.

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

Latona answered 16/1, 2022 at 0:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.