引言;有时候有些项目需求,直接使用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
                  
                  
                  
                  
                            
本文介绍了在Java中如何调用外部程序,包括两种常见方法:Runtime.getRuntime().exec() 和 ProcessBuilder.start(),并详细讲解了使用Runtime.exec()时涉及的Process类的主要函数及其用途。在实际项目中,常常借助这些功能来执行外部程序以满足特定需求。
          
      
          
                
                
                
                
              
                
                
                
                
                
              
                
                
              
            
                  
					208
					
被折叠的  条评论
		 为什么被折叠?
		 
		 
		
    
  
    
  
            


            