文章出處

下面是一個例子,演示如何執行一個進程(類似于在命令行下鍵入命令),讀取進程執行的輸出,并根據進程的返回值判斷是否執行成功。一般來說,進程返回 0 表示執行成功,其他值表示失敗。

import java.io.*;

/**
 * 示例:執行進程并返回結果
 */
public class ProcessExecutor {

    public static final int SUCCESS = 0;            // 表示程序執行成功

    public static final String COMMAND = "java.exe -version";    // 要執行的語句

    public static final String SUCCESS_MESSAGE = "程序執行成功!";

    public static final String ERROR_MESSAGE = "程序執行出錯:";

    public static void main(String[] args) throws Exception {

        // 執行程序
        Process process = Runtime.getRuntime().exec(COMMAND);

        // 打印程序輸出
        readProcessOutput(process);

        // 等待程序執行結束并輸出狀態
        int exitCode = process.waitFor();

        if (exitCode == SUCCESS) {
            System.out.println(SUCCESS_MESSAGE);
        } else {
            System.err.println(ERROR_MESSAGE + exitCode);
        }
    }

    /**
     * 打印進程輸出
     *
     * @param process 進程
     */
    private static void readProcessOutput(final Process process) {
        // 將進程的正常輸出在 System.out 中打印,進程的錯誤輸出在 System.err 中打印
        read(process.getInputStream(), System.out);
        read(process.getErrorStream(), System.err);
    }

    // 讀取輸入流
    private static void read(InputStream inputStream, PrintStream out) {
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

            String line;
            while ((line = reader.readLine()) != null) {
                out.println(line);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {

            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
 

文章列表


不含病毒。www.avast.com
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()