java调用外部程序的方法及代码演示

java调用外部程序的方法

在一个java应用中,可能会遇到这样的需求,就是需要调用一些外部的应用做一些处理,比如调用excel,然后在继续程序的运行。

下面就开始进入java调用外部程序的一些演示,让java应用更加灵活。

1:最简单的演示:

Runtime.getRuntime().exec("notepad.exe");

记事本被打开了是吧。

2:传递应用程序的参数:

Runtime runtime=Runtime.getRuntime();

String[] commandArgs={"notepad.exe","c:/boot.ini"};

runtime.exec(commandArgs);

现在不单单打开了记事本,而且还装载了boot.ini文件是吧。

现在已经完全解决了调用外部程序的问题,不是吗,但是大家会发现exec方法是有返回值,那么继续我们的演示吧。

1:Process的waitFor:

Runtime runtime=Runtime.getRuntime();

String[] commandArgs={"notepad.exe","c:/boot.ini"};

Process process=runtime.exec(commandArgs);

int exitcode=process.waitFor();

System.out.println("finish:"+exitcode);

执行上面的代码以后发现不同的地方了吗,waitFor会使线程阻塞,只有外部程序退出后才会执行System.out.println("finish:"+exitcode);

这个功能很有用是吧,因为多数时候你都需要等待用户处理完外部程序以后才继续你的java应用。

2:Process的destroy:

Runtime runtime=Runtime.getRuntime();

String[] commandArgs={"notepad.exe","c:/boot.ini"};

final Process process=runtime.exec(commandArgs);

new Thread(new Runnable(){

@Override

public void run() {

try {

Thread.sleep(5000);

} catch (InterruptedException e) {}

process.destroy();

}}).start();

int exitcode=process.waitFor();

System.out.println("finish:"+exitcode);

这个演示稍微复杂了一些,如果你等待5秒,就会发现记事本自动关闭了,是的,这个就是destroy方法的作用,强制关闭调用的外部程序。

不用我解释了吧,这是非常有用的方法。

以上的部分已经足够你调用并控制你的外部应用了。如果需要更详细的信息,看javadoc文档吧。

最后的说明:ProcessBuilder这个1.5新增的类也可以完成同样的任务,Runtime就是调用了这个类。

原文地址:https://blog.51cto.com/u_5454003/6130533