Skip to content
johnklee edited this page Jun 9, 2015 · 7 revisions

Introduction

如果你需要 Java 執行外部的程式, 通常會使用到 Runtime 類別. 一個使用範例代碼如下:

#!/usr/bin/env groovy
import java.io.BufferedReader;
import java.io.InputStreamReader;

Runtime runtime = Runtime.getRuntime();
try
{
    Process process = runtime.exec("dir");
    BufferedReader sb = new BufferedReader(new InputStreamReader(process.getInputStream()));
    String line;
    while ((line = sb.readLine()) != null)
    {
        System.out.printf("%s\n", line);
    }
    System.out.printf("Return code=%d\n", process.waitFor());
}
catch (Exception e)
{
    e.printStackTrace()
}

什麼! 只是要執行命令 "dir" 居然要這麼多代碼! 這還沒完, 如果你要處理 stderr 還有更多的 code 要加, 甚至你可能希望非同步的執行外部程式或是同時執行多個外部程式. 透過底下介紹的類別 ExecCmd, 讓你更輕鬆執行外部程式.

功能介紹

Clone this wiki locally