- Execute an external program and capture the output

Execute an external program and capture the output


 import java.io.*;
 public class CmdExec {
   public CmdExec(String cmdline) {
     try {
      String line;
      Process p = Runtime.getRuntime().exec(cmdline);
      // jdk1.0.2
      DataInputStream input = 
        new DataInputStream(p.getInputStream());
      // jdk1.1.1
      // BufferedReader commandResult = 
      //  new BufferedReader
      //    (new InputStreamReader(p.getInputStream()));
      while ((line = input.readLine()) != null) {
        System.out.println(line);
        }
      input.close();
      } 
     catch (Exception err) {
      System.out.println("EXEC failed: " + err.toString());
      err.printStackTrace();
      }
    }

 public static void main(String argv[]) {
   /*
   **  javac CmdExec tree.com
   **  javac CmdExec "tree.com /a"
   */
   new CmdExec(argv[0]);
   }
 }

You can include a path for the program to be executed. On the Win plateform, you will have
problem if the path contains spaces in it. To fix the problem, put the path in quotes.


  public class Test {
    public static void main(String[] args) throws Exception {
      Process p = Runtime.getRuntime().exec(
        "/"c:/program files/windows/notepad.exe/"");
         p.waitFor();
      }
   }

  • 0
    点赞
  • 0
    收藏
  • 打赏
    打赏
  • 0
    评论
©️2022 CSDN 皮肤主题:大白 设计师:CSDN官方博客 返回首页
评论

打赏作者

wxyxl

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值