在Java中运行一个外部程序

本文介绍如何使用Java的Runtime类来执行外部程序,并通过Process类获取其标准输出、错误输出和输入流。提供了运行ping命令并捕获输出的示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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


另外两个简单例子:用java调用ie浏览器(iexplore.exe与类文件在同一目录)


import java.io.*;
class Main {
public static void main(String[] args) {
try {
String cmd = "iexplore.exe ";
String param ="http://www.java3z.com/";
Process child = Runtime.getRuntime().exec(cmd+param);
// 获得ping的输出

} catch (IOException e) {
System.err.println(e);
}
}
}

在jdk1.5中可以这样:
import java.io.*;
public class ProcessTest {
public static void main(String args[]) throws IOException {
Process p = new ProcessBuilder("iexplore.exe","http://www.java3z.com/").start();
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值