首页
论坛
图书
开发资料
在线文档
网址
下载
联系我们
 新闻│Java│JavaScript│Eclipse│Eclipse 英文│J2EE│J2ME│J2SE│JSP│Netbeans│Hibernate│JBuilder│Spring│Struts
站内搜索: 请输入搜索关键词

当前页面: 开发资料首页 → Java 专题 → 在Java中运行一个外部程序

在Java中运行一个外部程序

摘要: 在Java中运行一个外部程序

</td> </tr> <tr> <td height="35" valign="top" class="ArticleTeitle"> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="431" height="86" align="center" valign="top">

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


</td> <td width="253" valign="top"> </td> </tr> <tr> <td height="20" colspan="2">


</td> </tr> </table>

 


</td> </tr> <tr>


↑返回目录
前一篇: Scanner类的用法
后一篇: CNDS社区java杂志第二期:J2SE 5.0新特性精解

首页 | 全站 Sitemap | 联系我们 | 设为首页 | 收藏本站
版权所有 Copyright © 2006-2007, Java 编程资料牛鼻站, All rights reserved