The intersection of technology and leadership

Executing native processes in Java on Windows

This is probably something that old timers in Java will probably know, so I’m posting this more for my reference. Trying to execute:

Runtime.getRuntime().exec("dir");

results in the following stack trace.

java.io.IOException: CreateProcess: dir error=2
  at java.lang.ProcessImpl.create(Native Method)
  at java.lang.ProcessImpl.(ProcessImpl.java:81)
  at java.lang.ProcessImpl.start(ProcessImpl.java:30)
  at java.lang.ProcessBuilder.start(ProcessBuilder.java:451)
  at java.lang.Runtime.exec(Runtime.java:591)
  at java.lang.Runtime.exec(Runtime.java:429)
  at java.lang.Runtime.exec(Runtime.java:326)

After doing some reading

error=2

apparently means file not found. The fix for something like this is to first pass everything to the windows command line shell (cmd.exe on windows xp). This seems to do the job better:

Runtime.getRuntime().exec("cmd /c dir");

The slash-C means “Carries out the command specified by string and then terminates”.

4 Comments

  1. johnstok

    Patrick,

    The best doc’s that I’ve managed to find on Windows error codes is the following:
    * http://msdn.microsoft.com/en-us/library/ms681381.aspx

    In the long run, the java.lang.ProcessBuilder class might be a better option, depending on what you’re trying to achieve.

    Be aware when using process builder that there are two concepts of directory:

    1. The directory in which you want the process to execute.

    2. The directory that contains the executable file.

    Confusing the two (the doc’s don’t make the distinction v’ well) often leads to ‘error=2’ because Java can’t find the executable you want to run…

  2. Tormod Haugen

    Hi,

    Strange coincidence; I was asked about exactly this today. A quick google turned up with a nice howto on Java and processes, including examples on different programs (including for Mac and Linux) and usage of the ProcessBuilder.

  3. Patrick

    Hi guys,

    Thanks for the comments. I will take a look at ProcessBuilder as well.

    Cheers!

  4. Anonymous

    fuck windows
    long live GNU
    😉

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

© 2024 patkua@work

Theme by Anders NorenUp ↑