Running a program from within Java code

徘徊边缘 提交于 2019-12-08 04:13:19

问题


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).


回答1:


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.




回答2:


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.




回答3:


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




回答4:


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.



来源:https://stackoverflow.com/questions/845654/running-a-program-from-within-java-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!