服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

如何运行一个外部程序并捕获输出


  在java中运行一个外部程序是使用java.lang.runtime类的方法exec().该方法返回一个process类。 如果你想捕获运行程序的输出,就要使用process类。process类有三个方法:. process.getoutputstream(), process.getinputstream(), process.geterrorstream().分别对应于stdin, stdout, stderr。因此 如果想要捕捉该程序的输出,就要使用process.getinputstream()。下面我给的例子就是运行ping程序,然后 把它的输出打印到屏幕上。所产生的效果和直接运行ping 程序是一样的。
  对于process类的其他方法的使用例子,请大家下载我所提供jdk1.1类库api例子。
  
  
  import java.io.*;
  
  class main {
   public static void main(string[] args) {
   try {
   string cmd = "ping ";
  string param ="202.112.58.200";
   process child = runtime.getruntime().exec(cmd+param);
   // 获得ping的输出
   inputstream child_in = child.getinputstream();
   int c;
   while ((c = child_in.read()) != -1) {
  // system.out.println("kkk");
   system.out.print((char)c);
   }
   child_in.close();
   } catch (ioexception e) {
   system.err.println(e);
   }
   }
  }

扫描关注微信公众号