3

I am trying to run set command from eclipse, but i am getting the below exception.

java.io.IOException: Cannot run program "set": CreateProcess error=2, The system cannot find the file specified
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)
    at java.lang.Runtime.exec(Runtime.java:620)
    at java.lang.Runtime.exec(Runtime.java:450)
    at java.lang.Runtime.exec(Runtime.java:347)

Here is my piece of code:

String command = "set Path=C:/Program Files/Java/jdk1.6.0_21/bin";
Process p = Runtime.getRuntime().exec(command);
Madhawa Priyashantha
  • 9,633
  • 7
  • 33
  • 60
HimaaS
  • 413
  • 3
  • 6
  • 13

1 Answers1

10

The program fails because set is not an executable but a command inside the command processor cmd.exe.

To invoke it use

String command = "cmd.exe /c set path=C:/Program Files/Java/jdk1.6.0_21/bin";
Process p = Runtime.getRuntime().exec(command);

But be aware of the pitfalls of setting environment variables, see How to set an environment variable in Java using exec? as mentionend in the comments by @Berger

Community
  • 1
  • 1
wero
  • 32,544
  • 3
  • 59
  • 84
  • Have doubt that, ping command is working without adding 'cmd' before it.then why only set has this problem, can u please elaborate the reason why should i use 'cmd'? – HimaaS Apr 06 '16 at 10:57
  • Windows has a `ping.exe` and therefore you can start it using `Runtime.exec` but there is no `set.exe` (and no `echo.exe`, `dir.exe` ...) – wero Apr 06 '16 at 11:04
  • Thanks a lot. it is really amazing.. – HimaaS Apr 06 '16 at 11:16