引言;有时候有些项目需求,直接使用java编写比较麻烦,所有我们可能使用其他语言编写的程序来实现。那么我们如何在java中调用外部程序,幸好
java为我们提供了这样的功能。
一.调用外部程序接口
方法1.
Process p=Runtime.getRuntime.exec("cmd")(最常用)
方法2.
Process p=new ProcessBuilder(cmd).start()
但是一般方法一比较常用, 下面我们介绍下方法一中关于抽象Process类的常用函数
//向对应程序中输入数据
abstract public OutputStream getOutputStream();
//获得对应程序的输出流(没写错)
abstract public InputStream getInputStream();
//获得程序的错误提示
abstract public InputStream getErrorStream();
//等待程序执行完成,返回0正常,返回非0失败
abstract public int waitFor() throws InterruptedException;
//获得程序退出值,0正常退出,非0则异常
abstract public int exitValue();
//销毁进程
abstract public void destroy();
其中前3个函数用的最多
二.代码实战
package test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class testProcess {
public static void main(String[]args) throws IOException, InterruptedException{
Runtime r=Runtime.getRuntime();
Process p=r.exec("python /home/cristo/桌面/test.py");
InputStream is=p.getInputStream();
InputStreamReader ir=new InputStreamReader(is);
BufferedReader br=new BufferedReader(ir);
String str=null;
while((str=br.readLine())!=null){
System.out.println(str);
}
//获取进程的返回值,为0正常,为2出现问题
int ret=p.waitFor();
int exit_v=p.exitValue();
System.out.println("return value:"+ret);
System.out.println("exit value:"+exit_v);
}
}
test.py中内容
for i in range(10):
print("current i value:%s\n"%i)
程序执行结果:
current i value:0
current i value:1
current i value:2
current i value:3
current i value:4
current i value:5
current i value:6
current i value:7
current i value:8
current i value:9
return value:0
exit value:0