不知道大伙有没有遇到类似的问题, 你用java搭建了一个系统平台,却发现你想引入的一个组件是用其它语言写成的。 如果那个组件是用c写的,你或许会想用java native code就可解决,但是如果那个组件是用perl, python, ruby写的,你又该如何呢? 如果你没有那个组件的源代码, 只有该组件已编译好的程序,你又该如何呢?
这种问题不是不可能发生的,本人从事数据挖掘系统的开发,之前就遇到这样的问题。我在网上找到了一个很好的分类算法-c4.5, 那是个开源软件, 用c写成的,非常复杂难读。另一方面,我们担心如果硬把这个c程序改成 java程序,它的运行效率会下降,正所谓是吃力不讨好。最后我们找到了‘使用java直接执行外部程序’ 这个方法来解决问题。
方法很简单,其实只要使用两个在java.lang包中的类就能解决,一个是java.lang.Runtime, 另一个为java.lang.Process, 费话少说,各位懂行的看官,请看代码:
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class ExeAgent {
/**
* @rwang
*/
/*
Class Runtime is the object to run external program
Class Process is the object to handle the outputs
*
*/
public static void execute(String commands){
try {
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec(commands); // Exception need to be handle
BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line=null;
while((line=input.readLine()) != null) {
System.out.println(line);
}
} catch(Exception e) {
System.out.println(e.toString());
e.printStackTrace();
}
}
public static void main(String[] args) {
String line = "java HelloWorld"; // java HelloWorld 是一个可执行命令, 任何可执行命令(程序)都可以替换它
// String line = "dir" dir命令将会被执行
ExeAgent.execute(line);
}
}
如果希望JVM等候外部命令完成执行后, 再继续执行余下命令行。 可以使用 waitFor() 方法, 例代码为:
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec(commands); try{ int status = pr.waitFor();
}catch(InterruptedException e){}