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

王朝other·作者佚名  2008-05-31
窄屏简体版  字體: |||超大  

在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);

}

}

}

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航