views:

330

answers:

4

Hi all,

What is the simplest way to call a program from with a piece of Java code? (The program I want to run is aiSee and it can be run from command line or from Windows GUI; and I am on Vista but the code will also be run on Linux systems).

+4  A: 

Take a look at Process and Runtime classes. Keep in mind that what you are trying to accomplish is probably not platform independent.

Here is a little piece of code that might be helpful:

public class YourClass
{
    public static void main(String args[])
       throws Exception
    {
        Runtime rt = Runtime.getRuntime();
        Process proc = rt.exec("name_of_your_application.exe");
        int exitVal = proc.exitValue();
        System.out.println("Process exitValue: " + exitVal);
    }
}

One question in S.O. discussing similiar issues. Another one. And another one.

Pablo Santa Cruz
Ok, thanks a lot. Yeah you're right: it cannot possibly be platform independent (since the two systems will probably have the program in different place). What I was thinking with that?
A: 

The difficulty you will run into is how to get the application to know the path. You may want to use an xml or config file, but if you use this link, it should explain how to run a file: http://www.javacoffeebreak.com/faq/faq0030.html

James Black
I'll probably just have passed as a command line arg, as Nathan suggested. It is awkward, but it'll have to do
+1  A: 

You can get a runtime instance using Runtime.getRuntime() and call the runtime's exec method, with the command to execute the program as an argument.

For example:

Runtime runTime = Runtime.getRuntime ();       
Process proc = rt.exec("iSee.exe");

You can also capture the output of the program by using getting the InputStream from the process.

nstehr
okay, thank you; though, since the output is graphic (aiSee displays graphs from GDL descriptions) I probably won't be processing it further; but it's good to know I have that option
A: 

You may also want to consider passing in some kind of argument to your program to facilitate finding the specific program you want to run.

This could be with command line arguments, properties files or system properties.

Nathan Feger