2012-10-25

在 Java 呼叫外部程式(Command-line or Application)

這是很基本的工具程式,但是不會想去記起來,卻每隔一陣子就會用到。
public class ExecCmd {

  public static void main(String args[]) {
    try {
      Process pr = Runtime.getRuntime().exec("ipconfig");
      BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream(), "MS950"));
      String line = null;
      while ((line = input.readLine()) != null) {
        System.out.println(line);
      }
      int exitVal = pr.waitFor();
      System.out.println("Exit code " + exitVal);
    }
    catch (Exception e) {
      e.printStackTrace();
    }
  }
}
---
---
---

沒有留言:

張貼留言