user1414413
user1414413

Reputation: 403

Passing a path to exec

I am trying to use the exec function. The path to the executable contains spaces and this is giving me grief My code looks like this

Runtime.getRuntime().exec("\"C:\\Program Files (x86)\\ASL\\_ASL Software Suite_installation.exe\"", null, new File("\"C:\\Program Files (x86)\\ASL\\_ASL Software Suite_installation\""));

When this is executed I get an exception -

Cannot run program ""c:\Program" 

I would be grateful if someone can give me some help in solving this

Thanks in advance

Upvotes: 0

Views: 1910

Answers (2)

hmjd
hmjd

Reputation: 122011

From Runtime.exec(String command, String[] envp, File dir):

Executes the specified string command in a separate process with the specified environment and working directory.

This is a convenience method. An invocation of the form exec(command, envp, dir) behaves in exactly the same way as the invocation exec(cmdarray, envp, dir), where cmdarray is an array of all the tokens in command.

More precisely, 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.

This means the first string is broken into tokens, regardless of the outer quotes. Use the Runtime.exec(String[] cmdarray, String[] envp, File dir) version to avoid the tokenization of the executable path.

Or, use ProcessBuilder:

File d = new File("C:/Program Files (x86)/ASL/_ASL Software Suite_installation");
ProcessBuilder pb = new ProcessBuilder(d.getAbsolutePath() + "/main.exe");
Process p = pb.directory(d)
              .start();

See:

Upvotes: 4

shyam
shyam

Reputation: 9368

You don't need to quote the filenames again. Java will take care of it for you just give the proper filename as a string like so

Runtime.getRuntime().exec(
    "C:\\Program Files (x86)\\ASL\\_ASL Software Suite_installation.exe", 
    null, 
    new File("C:\\Program Files (x86)\\ASL\\_ASL Software Suite_installation"));

Upvotes: -1

Related Questions