“Cannot run program” when using Runtime.exec with

2020-04-17 06:12发布

问题:

I am using the below code to open the "sample.html' file.

String filename = "C:/sample.html";

String browser = "C:/Program Files (x86)/Google/Chrome/Application/chrome.exe";

Runtime rTime = Runtime.getRuntime();

Process pc = rTime.exec(browser + filename);

pc.waitFor();

However, I am getting the below error.

java.io.IOException: Cannot run program "C:/Program": CreateProcess error=2, The system cannot find the file specified

Could someone please help me figure this. Thanks in advance.

回答1:

Runtime.exec(String) automatically splits the string at spaces, assuming the first token is the command name and the rest are command line parameters. Also you do not have a space between browser and file, although that is not the root cause of the problem.

It thinks you want to run "C:/Program" with two command line arguments:

  1. "Files"
  2. "(x86)/google/Chrome/Application/chrome.exeC:/sample.html"

Use Runtime.exec(String[]) instead, that way you have full control over what is what:

 String[] command = new String[]{browser, filename};
 Runtime.exec(command);


回答2:

Try this.

    String filename = "C:\\sample.html";
    String browser = "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe";

    Runtime runtime = Runtime.getRuntime();

    try {
        runtime.exec(new String[] {browser, filename});
    } catch (IOException e) {
        e.printStackTrace();
    }


回答3:

Stop using Runtime.exec(String) - the problem is in how it processes the single string input.

The error message indicates how/where it is failing: note that it stops after "C:/Program" (or, the first space). This indicates that exec parsed the string "incorrectly" and thus isn't even looking for the correct executable.

Cannot run program "C:/Program"

Instead, consider the use of ProcessBuilder. While the usage is still system-dependent, ProcessBuilder allows separation of the executable file-name (and need to deal with it specially) and the arguments and does it's darnedest to invoke the target correctly.

String filename = "C:\\sample.html";
String browser = "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe";

ProcessBuilder pb = new ProcessBuilder(browser, filename);
// setup other options ..
// .. and run
Process p = pb.start();
p.waitFor();

From what I can tell, in Windows, ProcessBuilder will wraps the individual components in quotes; this can create a different problem when arguments contain quotes..



回答4:

Parameters must be passed separately:

Process pc = rTime.exec(new String[]{browser, filename});

Using exec() is not like using the command line - you can not use spaces to delimit the command from its parameters. Your attempt would try to execute a command whose path was the concatenation of the exec and the filename as one giant string.