Java Cookbook之Java调用外部程序



Problem 1:

    在Java程序内运行一个外部的程序.

Solution:

    在java.lang.Runtime 类中运用其exec()方法,或者设置一个ProgressBuilder建造器进而调用其start()方法.


实例如下:

   public class ExecDemoSimple {    public static void main(String av[]) throws Exception {
        // Run the "notepad" program or a similar editor    

        Process p = Runtime.getRuntime().exec("kwrite");
        p.waitFor(); 

    }


  } 


Problem2:Java调用外部程序并捕获输出.


public class ExecDemoLs {   

 /** The program to run */   

 public static final String PROGRAM = "ls";

 // "dir" for Windows    

/** Set to true to end the loop */   



  static volatile boolean done = false;
  public static void main(String argv[]) throws IOException {
        final Process p;  // Process tracks one external native process    

        BufferedReader is;  // reader for output of process

        String line;
        p = Runtime.getRuntime().exec(PROGRAM);
        Debug.println("exec", "In Main after exec");
        // Optional: start a thread to wait for the process to terminate.      

        // Don't just wait in main line, but here set a "done" flag and use that to control the main reading loop below.       




       Thread waiter = new Thread() {    

                     public void run() {             

                              try {                  

                                      p.waitFor();             

                                  } catch (InterruptedException ex) {  

                                      // OK, just quit.           

                                      return; 

                                 }    

                                 System.out.println("Program terminated!");      

                                 done = true;         

                             }   }; 

                                 waiter.start();




                       // getInputStream gives an Input stream connected to   the process p's standard output (and vice versa).

                       // We use  that to construct a BufferedReader so we can readLine() it.

                     is = new BufferedReader(new InputStreamReader(p.getInputStream()));
                     while (!done && ((line = is.readLine()) != null))  

                     System.out.println(line);

                     Debug.println("exec", "In Main after EOF");
                     return;    

        }

 } 





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值