在Java中运行一个外部程序

 在Java中运行一个外部程序是使用java.lang.Runtime类的方法exec().该方法返回一个Process类。 
             如果你想捕获运行程序的输出,就要使用Process类。Process类有三个方法:. 

    Process.getOutputStream(), Process.getInputStream(), Process.getErrorStream().

   分别对应于stdin, stdout, stderr。因此 如果想要捕捉该程序的输出,就要使用
             Process.getInputStream()。

下面我给的例子就是运行ping程序,然后把它的输出打印到屏幕上。 


 所产生的效果和直接运行ping 程序是一样的。              

 
            import java.io.*;
            class Main {
               public static void main(String[] args) {
               try {
               String cmd = "ping ";
               String param ="www.baidu.com";
               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 IETest
{
 public static void main(String[] args)
 {
  try {
   String cmd = "/"c://Program Files//Internet Explorer//IEXPLORE.EXE/"";
   String param ="http://www.baidu.com";
   Process child = Runtime.getRuntime().exec(cmd+param);
  } catch (IOException e)
  {
   System.err.println(e);
  }
 }
}

你可能感兴趣的:(在Java中运行一个外部程序)