简体   繁体   中英

Java exec and environment variable in command path

I try to execute a parameterized command with Runtime.exec() with environment variable in the command string.

Example:

  String cmd = "%ProgramFiles%\\Internet Explorer\\iexplore.exe";
  Runtime.getRuntime().exec(cmd);

I got the following error:

java.io.IOException: Cannot run program "%ProgramFiles%\Internet": CreateProcess error=2, Le fichier spécifié est introuvable
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:460)
    at java.lang.Runtime.exec(Runtime.java:593)
    at java.lang.Runtime.exec(Runtime.java:431)
    at java.lang.Runtime.exec(Runtime.java:369)
    at TestEnv.main(TestEnv.java:34)
Caused by: java.io.IOException: CreateProcess error=2, Le fichier spécifié est introuvable
    at java.lang.ProcessImpl.create(Native Method)
    at java.lang.ProcessImpl.<init>(ProcessImpl.java:81)
    at java.lang.ProcessImpl.start(ProcessImpl.java:30)
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:453)
    ... 4 more

Without environment variable in the command it works and launches IE:

  String cmd = "C:\\Program Files\\Internet Explorer\\iexplore.exe";
  Runtime.getRuntime().exec(cmd);

I checked ProgramFiles variable exists:

  String path = System.getenv("ProgramFiles");
  System.out.println(path);

This returns well C:\\Program Files

I tried to put manually the variable, same error:

  Runtime.getRuntime().exec(cmd, new String[] {"ProgramFiles=C:\\Program Files"});

I tried with ProcessBuilder, same error:

  ProcessBuilder pb = new ProcessBuilder(cmd);
  pb.start();

What is the good way to do this, is it possible?

I can't speak directly about Windows, but exec is directly looking up the command path and trying to run it. Putting env vars in the path doesn't help as its the shell that deals with env vars, not the exec.

Since the JRE closely mimics the Unix OS what normally would be done is using a two arg exec with one of the args being the env vars. But java didn't chose to enable that route.

So my advice is to put the vars directly into the JVM env and then exec the command.

Or something more windows that someone will follow up this post with.

use this to get the value

String ProgramFiles = System.getenv("ProgramFiles");

then concat it to the command

String cmd = ProgramFiles + "\\Internet Explorer\\iexplore.exe";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM