Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java execute a command with a space in the pathname

Tags:

java

How can I execute a Java System (shell) command that has a space in the pathname?

I've tried putting quotes and a backslash (), But it does not work.

ln -s "dir1/dir2" "my\ dir/dir2"
like image 593
LanguagesNamedAfterCofee Avatar asked Feb 06 '11 23:02

LanguagesNamedAfterCofee


3 Answers

By far the most reliable way is to use Runtime.exec(String[] cmdarray).

If you use Runtime.exec(String command), Java only splits the command on whitespace.

the command string is broken into tokens using a StringTokenizer created by the call new StringTokenizer(command) with no further modification of the character categories. The tokens produced by the tokenizer are then placed in the new string array cmdarray, in the same order.

See also g++: File not found

Or use ProcessBuilder something like this:

ProcessBuilder pb = new ProcessBuilder("ln", "-s", "dir1/dir2", "my dir/dir2");
Process p = pb.start();
like image 119
Mikel Avatar answered Nov 15 '22 09:11

Mikel


Do you really need to execute it in a shell (e.g. do you need to shell expansion of things like ~ or *, etc)? If not, you could invoke ln directly:

Process p =
    Runtime.getRuntime()
    .exec(new String[]{"/bin/ln","-s","dir1/dir2", "my\\ dir/dir2"});

If you really need a shell, try this (this may need a little tweaking depending on how the shell processes the quotes):

Process p =
    Runtime.getRuntime()
    .exec(new String[]{"/bin/sh", "-c", "ln -s \"dir1/dir2\" \"my\\ dir/dir2\""});

Edit:

I was under the impression the second path has a literal backslash in it. If it's not supposed to remove the \\ from the string literals above.

like image 30
Bert F Avatar answered Nov 15 '22 08:11

Bert F


None of these work on Lion. However, the following does work, and is backwards compatible for Tiger.

Runtime.getRuntime().exec(new String[]{"/bin/bash","-c","/path/to/file/space*init"});
like image 1
Hoverfrog Avatar answered Nov 15 '22 09:11

Hoverfrog