PDA

View Full Version : How do you run a .exe file in java?


JB4
08-01-2007, 06:44 AM
I've been trying to get this to work, and i cant even begin to figure it out...

all i want to do, is open "C:\windows\notepad.exe" and then print on screen, "loaded"

please help me!

jkim
08-01-2007, 09:58 AM
try {
// TODO: Some stuff
Runtime.getRuntime().exec("notepad.exe");
// TODO: Some other stuff
} catch (Exception e) {
// TODO: Other error handling
e.printStackTrace();
}

Aradon
08-01-2007, 06:32 PM
try {
// TODO: Some stuff
Runtime.getRuntime().exec("notepad.exe");
// TODO: Some other stuff
} catch (Exception e) {
// TODO: Other error handling
e.printStackTrace();
}

To give a quick explanation about what is going on here, Java has this class called Runtime which you can use to get the current runtime environment After getting that you can execute a command on that environment. In this example, we want to run notepad and so we do. After you do that you can do a System.out.println of Loaded and then you're done.

But because of exception handling (and thank god for it) you have to place this within a try catch block just to make sure that nothing goes wrong while your program is running. There are lots of other things you can do with the Runtime as well which can be seen here:

Runtime (http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Runtime.html)